Problems with a tile worldscreen system? - c#

Im trying to make a tile based world screen for my game , here are the three classes i have
namespace WindowsGame1
{
public enum Tiletype
{Grass,
Water,
Foothill,
Mountain
}
public struct Tile
{
public Tiletype TerrainType { get; set; }
public Texture2D TileGFX { get; set; }
public Rectangle SrcRect { get; set; }
public Vector2 Location { get; set; }
public int AniFrame { get; set; }
// TILE ACTIONS
public bool IsActivated { get; set; }
public bool IsBlocked { get; set; }
public bool IsTouchTrigger { get; set; }
public bool IsStepTrigger { get; set; }
}
}
MapBase class
public class MapBase
{
public Tile[,] TileList = new Tile[1, 1];
public MapBase(int width, int height, Vector2 start)
{
TileList = new Tile[width + 1, height + 1];
// TEMPORARY MAP
for (int X = 0; X <= width; X++)
{
for (int Y = 0; Y <= height; Y++)
{
TileList[X, Y] = new Tile();
var _with1 = TileList[X, Y];
_with1.TerrainType = Tiletype.Water;
_with1.TileGFX = Textures.World;
_with1.AniFrame = 0;
_with1.IsBlocked = true;
}
}
// SIMPLE ISLAND
for (int z = 22; z <= 33; z++)
{
for (int c = 22; c <= 31; c++)
{
TileList[z, c].TerrainType = Tiletype.Grass;
}
}
TileList[27, 25].TerrainType = Tiletype.Foothill;
TileList[28, 25].TerrainType = Tiletype.Foothill;
TileList[27, 24].TerrainType = Tiletype.Foothill;
TileList[28, 26].TerrainType = Tiletype.Mountain;
for (int x = 0; x <= width; x++)
{
for (int y = 0; y <= height; y++)
{
TileList[x, y].SrcRect = GetTileSource(TileList[x, y].TerrainType);
}
}
}
GetTitleSource function
private Rectangle GetTileSource(Tiletype TType)
{
Rectangle sRect = default(Rectangle);
switch (TType)
{
case Tiletype.Grass:
sRect = new Rectangle(0, 0, 16, 16);
break;
case Tiletype.Water:
sRect = new Rectangle(0, 80, 16, 16);
break;
case Tiletype.Foothill:
sRect = new Rectangle(48, 0, 16, 16);
break;
case Tiletype.Mountain:
sRect = new Rectangle(32, 0, 16, 16);
break;
}
return sRect;
}
}
Class WorldScreen
class Worldscreen : BaseScreen
{
public int MapWidth = 100;
public int MapHeight = 100;
public int TileSize = 32;
public int MapX = 20;
public int MapY = 19;
public MapBase Map = new MapBase(100, 100, new Vector2(0, 0));
public Worldscreen(GraphicsDevice device)
: base(device, "WorldScreen")
{
Map = new MapBase(MapWidth, MapHeight, new Vector2(0, 0));
}
Draw function
public override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
Globals.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone);
//DRAW TILE LAYER
for (int DrawX = -1; DrawX <= 16; DrawX++)
{
for (int DrawY = -1; DrawY <= 15; DrawY++)
{
int x = DrawX + MapX;
int y = DrawY + MapY;
if (x > 0 & x <= MapWidth & y >= 0 & y <= MapHeight)
{
Globals.spriteBatch.Draw(Map.TileList[x,y].TileGFX, new Rectangle(DrawX * TileSize, DrawY * TileSize, TileSize, TileSize), Map.TileList[x, y].SrcRect, Color.White);
// VIEW COORDINATES ON TILE
//Globals.SpriteBatch.DrawString(Fonts.Arial_8, "X:" & x & vbCrLf & "Y:" & y, New Vector2(DrawX * TileSize, DrawY * TileSize), Color.Black)
}
}
}
Globals.spriteBatch.End();
}
}
When I try to run the draw void it comes up with this error on the world screen class
This method does not accept null for this parameter.
Parameter name: texture
is there any way to solve this or do i have to rework these classes.

you got all the info you need to debug this yourself :
theres a method on the world screen class who have a texture = null.
Go step-by-step debug and find out which one, unless its a simple error we can find looking at your code, but its often not that easy. ( ex : do you have a list which isnt instanciate ? )
but since its a method paramaters ... the only method that accept a texture as a parameter is GetTileSource.
So quickly what could explain it ... I'd check 2 things :
A- are you sure your loop have correct bound ? You might simply be asking for a tile in that array that doesn't exist since its out of bound. (array are 0 base, and you loop up to <= height instead of < height)
B- 2nd thing i'd check would be (since this is a texture ) that you didn't load one of those texture you use ...

Related

About Unity A* (Astar) Pathfinding

I apologize if I irritate you as I am still very new to programming programming.
I am currently learning to work with Astar Pathfinding in Unity.
I am also currently referencing code for several Astar algorithms, many of which also introduce map generation code.
This question is about that map generation code, but I would appreciate it if you could answer it in connection with Astar Pathfinding, if possible.
The following code is introduced by a Japanese programmer.
I have a question about "public static Coord operator +(Coord a, Coord b) {return new Coord(a.x +a.y, b.x + b.y); }" in public struct Coord in the following code.
What do the "a and b" in a.x and b.x mean?
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class AStarGrid
{
public enum GroundType
{
NotRoad,
Road,
}
/// <summary>
/// 座標
/// </summary>
[System.Serializable]
public struct Coord
{
public int x;
public int y;
public static Coord zero = new Coord(){ x = 0, y = 0 };
public static Coord one = new Coord(){ x = 1, y = 1 };
public static Coord left = new Coord(){ x = -1, y = 0 };
public static Coord up = new Coord(){ x = 0, y = 1 };
public static Coord right = new Coord(){ x = 1, y = 0 };
public static Coord down = new Coord(){ x = 0, y = -1 };
public static Coord operator +(Coord a, Coord b)
{ return new Coord(a.x + b.x, a.y + b.y); }
public static Coord operator -(Coord a, Coord b)
{ return new Coord(a.x - b.x, a.y - b.y); }
public float SqrMagnitude { get { return x * x + y * y; } }
public float Magnitude { get { return Mathf.Sqrt(SqrMagnitude); } }
public Coord(int x, int y)
{
this.x = x;
this.y = x;
}
}
/// <summary>
/// Cell
/// </summary>
[System.Serializable]
public class Cell
{
public Coord coord;
public GroundType groundType;
}
[SerializeField]
private List<Cell> _cells;
public List<Cell> Cells { get { return _cells; } }
[SerializeField]
private int _columnCount;
public int ColumnCount { get { return _columnCount; } }
[SerializeField]
private int _rowCount;
public int RowCount { get { return _rowCount; } }
[SerializeField]
private Coord _startCellCoord;
public Cell StartCell { get { return GetCell(_startCellCoord); } set { _startCellCoord = value.coord; } }
[SerializeField]
private Coord _goalCellCoord;
public Cell GoalCell { get { return GetCell(_goalCellCoord); } set { _goalCellCoord = value.coord; } }
public AStarGrid(int columnCount, int rowCount)
{
_columnCount = columnCount;
_rowCount = rowCount;
_cells = new List<Cell>();
for (int i = 0; i < columnCount * rowCount; i++) {
var column = Mathf.FloorToInt(i / rowCount);
var row = i % rowCount;
var coord = new Coord(){ x = column, y = row };
_cells.Add(new Cell(){ coord = coord });
}
}
/// <summary>
/// get cell
/// </summary>
public Cell GetCell(Coord coord){
return GetCell(coord.x, coord.y);
}
/// <summary>
/// get cell
/// </summary>
public Cell GetCell(int x, int y)
{
if (IsValidCoord(x, y)) {
var index = x * _rowCount + y;
return _cells[index];
}
else {
return null;
}
}
/// <summary>
/// Does the cell exist?
/// </summary>
public bool IsValidCoord(int x, int y)
{
return x >= 0 && x < _columnCount && y >= 0 && y < _rowCount;
}
/// <summary>
/// get neighbor cells
/// </summary>
public List<Cell> GetAdjacences(int x, int y)
{
var adjacences = new List<Cell>();
var offsets = new Coord[] { Coord.left, Coord.up, Coord.right, Coord.down };
for (int i = 0; i < offsets.Length; i++) {
var cell = GetCell(x + offsets[i].x, y + offsets[i].y);
if (cell != null) {
adjacences.Add(cell);
}
}
return adjacences;
}
}
a and b are references to instances of Cord struct witch contains x and y variables witch you have access to by using . After name of instance of a class/struct also these a and b means if u use - between two cords it will do the math of x of a minus x of b and so on

JsonConvert.DeserializeObject loading data types but not data values

My program gives the user the option to serialize a certain list List<Position>ListPosition that stores the data from the class Position. It does serialize pretty well and it sorta looks like the following
{
"PosZ": 0,
"PosX": 749,
"PosY": 208,
"Agent": {
"IsEdgeTree": false,
"ThisTreesCreator": null,
"Type": 0,
"Colour": "Green",
"Dimension": 25
}
},
{
"PosZ": 0,
"PosX": 724,
"PosY": 183,
"Agent": {
"IsEdgeTree": false,
"ThisTreesCreator": {
"IsEdgeTree": false,
"Position": {
"PosZ": 0,
"PosX": 749,
"PosY": 208
},
"ThisTreesCreator": null,
"Type": 0,
"Colour": "Green",
"Dimension": 25
},
"Type": 0,
"Colour": "Green",
"Dimension": 25
}
},
These are just a few examples.
The bit that is giving me problems is when I deserialize it.
When I inspect the bit of code that converts it JsonConvert.DeserializeObject<List<Position>>(JsonString);, everything reads fine but, when I equal it to the List I am trying to dump the data to AKA the same list the serialized data comes from but empty, the data doesn't load and I'm left with the correct structure but no values.
Values not showing up
To Deserialize, I call the following method from another Windows Forms:
public static void Deserialize()
{
if (Directory.Exists("Serialized"))
{
var FileName = "Serialized/PositionsSerialized_4.json";
var JsonString = File.ReadAllText(FileName);
ListPositions = JsonConvert.DeserializeObject<List<Position>>(JsonString);
}
else
MessageBox.Show("There's no directory");
}
I would really appreciate some help. If more information is needed, be sure to request it in the comments.
Thank you for your time.
public class Position
{
public static int MaxX { get; private set; }
public static int MaxY { get; private set; }
public static List<Position> ListPositions { get; private set; }
public static List<Position> ListTreePositions {
get
{
return ListPositions.Where(w => w.Agent?.Type == AgentType.Tree).ToList();
}
}
public static List<Position> ListDronePositions
{
get
{
return ListPositions.Where(w => w.Agent?.Type == AgentType.Drone).ToList();
}
}
public int PosX { get; private set; }
public int PosY { get; private set; }
public int PosZ;
private static object services;
public Agent Agent { get; private set; }
public Position()
{
ListPositions = new List<Position>();
}
public static void SetMaxValues(int maxX, int maxY)
{
MaxX = maxX;
MaxY = maxY;
}
public void FillNeighbours(int posX, int posY, int dim)
{
for (int i = 0; i < dim; i++)
{
for (int y = 0; y < dim; y++)
{
new Position(posX - (dim - y), posY - (dim - i), Agent);
}
}
}
public static Position CreateNewRandomPosition()
{
Random rnd = new Random();
int rndX;
int rndY;
Position position = null;
while (position == null)
{
rndX = rnd.Next(MaxX - 100);
rndY = rnd.Next(MaxY - 100);
position = CreatePosition(rndX, rndY);
}
return position;
}
public static Bitmap ExportBitmap()
{
return ExportBitmap(0, 0, MaxX, MaxY, ListPositions);
}
public static Bitmap ExportBitmap(int posX, int posY, int maxX, int maxY)
{
var listPositions = ListPositions.Where(w => (w.Agent != null) && (w.PosX >= posX && w.PosX <= maxX) && (w.PosY >= posY && w.PosY <= maxY)).ToList();
return ExportBitmap(posX, posY, maxX, maxY, listPositions);
}
public static Bitmap ExportBitmap(int posX, int posY, int maxX, int maxY, AgentType agentType)
{
var listPositions = ListPositions.Where(w => (w.Agent.Type == agentType) && (w.PosX >= posX && w.PosX <= maxX) && (w.PosY >= posY && w.PosY <= maxY)).ToList();
return ExportBitmap(posX, posY, maxX, maxY, listPositions);
}
public static Bitmap ExportBitmap(int posX, int posY, int maxX, int maxY, AgentType[] agentType)
{
var listPositions = ListPositions.Where(w => (agentType.Contains(w.Agent.Type)) && (w.PosX >= posX && w.PosX <= maxX) && (w.PosY >= posY && w.PosY <= maxY)).ToList();
return ExportBitmap(posX, posY, maxX, maxY, listPositions);
}
private static Bitmap ExportBitmap(int posX, int posY, int maxX, int maxY, List<Position> positions)
{
Bitmap bmp = new Bitmap(maxX - posX, maxY - posY);
if (Agent.Sprites.Count() == 0)
{
Agent.LoadSprites();
}
Graphics g = Graphics.FromImage(bmp);
foreach (var item in positions)
{
var SpriteWidth = Agent.Sprites[item.Agent.Type].Width / 2;
var SpriteHeight = Agent.Sprites[item.Agent.Type].Height / 2;
g.DrawImage(Agent.Sprites[item.Agent.Type], new Point(item.PosX - SpriteWidth - posX, item.PosY - SpriteHeight - posY));
}
if (!Directory.Exists("Photos"))
{
Directory.CreateDirectory("Photos");
}
int count = Directory.GetFiles("Photos", "*").Length;
bmp.Save("Photos\\Img" + count + 1 + ".png", System.Drawing.Imaging.ImageFormat.Png);
return bmp;
}
public Position(int poxX, int poxY)
{
PosX = poxX;
PosY = poxY;
if (Agent != null)
ListPositions.Add(this);
}
public Position(int posX, int posY, Agent agent)
{
PosX = posX;
PosY = posY;
Agent = agent;
if (Agent != null)
ListPositions.Add(this);
}
public void AssociateAgent(Agent agent)
{
Agent = agent;
if (Agent != null)
ListPositions.Add(this);
}
public static bool CheckPositionIsValid(int poxX, int poxY)
{
int? NullableMaxX = MaxX;
int? NullableMaxY = MaxY;
var posXValid = poxX > 0 && (poxX <= MaxX || NullableMaxX == null); //verifies if posX is within the boundries of the premises
var posYValid = poxY > 0 && (poxY <= MaxY || NullableMaxY == null); //verifies if posY is within the boundries of the premises
return posXValid && posYValid; //returns if they are both valid
}
public static Position Find(int poxX, int poxY)
{
return ListPositions.Find(f => f.PosX == poxX && f.PosY == poxY) ?? null;
}
public static Position CreatePosition(int poxX, int poxY)
{
if (Find(poxX, poxY) == null)
if (CheckPositionIsValid(poxX, poxY))
return new Position(poxX, poxY);
else
return null;
else
return null;
}
public Dictionary<int, Position> ListNeighbourPositions(int dim = 1)
{
Dictionary<int, Position> NeighbourList = new Dictionary<int, Position>();
for (int i = 1; i < 9; i++)
{
if (i != 5)
{
var position = FindNeighbour(i, dim);
if (position != null)
NeighbourList.Add(i, position);
}
}
return NeighbourList;
}
public Position FindNeighbour(int neighbourPos, int dim)
{
var position = FindNeighbourbyPosition(neighbourPos, dim);
return Find(position.Item1, position.Item2);
}
public Tuple<int, int> FindNeighbourbyPosition(int neighbourPos, int dim = 1)
{
int neighbourPosX;
int neighbourPosY;
switch (neighbourPos)
{
case 1:
neighbourPosX = PosX - dim;
neighbourPosY = PosY - dim;
break;
case 2:
neighbourPosX = PosX;
neighbourPosY = PosY - dim;
break;
case 3:
neighbourPosX = PosX + dim;
neighbourPosY = PosY - dim;
break;
case 4:
neighbourPosX = PosX - dim;
neighbourPosY = PosY;
break;
case 6:
neighbourPosX = PosX + dim;
neighbourPosY = PosY;
break;
case 7:
neighbourPosX = PosX - dim;
neighbourPosY = PosY + dim;
break;
case 8:
neighbourPosX = PosX;
neighbourPosY = PosY + dim;
break;
case 9:
neighbourPosX = PosX + dim;
neighbourPosY = PosY + dim;
break;
default:
return null;
}
return new Tuple<int, int>(neighbourPosX, neighbourPosY);
}
public void UpdatePosition(int newX, int newY)
{
PosX = newX;
PosY = newY;
}
public static void Serialize()
{
if (!Directory.Exists("Serialized"))
{
Directory.CreateDirectory("Serialized");
}
int count = Directory.GetFiles("Serialized", "*").Length;
string fileName = "Serialized/PositionsSerialized_" + count + ".json";
string jsonString = JsonConvert.SerializeObject(ListPositions, Formatting.Indented, new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
File.WriteAllText(fileName, jsonString);
}
public static void Deserialize()
{
if (Directory.Exists("Serialized"))
{
var FileName = "Serialized/PositionsSerialized_4.json";
var JsonString = File.ReadAllText(FileName);
ListPositions = JsonConvert.DeserializeObject<List<Position>>(JsonString);
}
else
MessageBox.Show("There's no directory");
}
}
The reason of your problem is because you defined setters as private...
public static int MaxX { get; private set; }
public static int MaxY { get; private set; }
public int PosX { get; private set; }
public int PosY { get; private set; }
it should be...
public static int MaxX { get; set; }
public static int MaxY { get; set; }
public int PosX { get; set; }
public int PosY { get; set; }

Find largest area using

I need to find largest area with same numbers in 2D array. Example: {{2 2 3}{1 2 3}{1 2 1}}
And mark it in new 2D array with same number for same area.
I will need to color the table with 3 colors, so i use between 1-3 in table[,]
I did test, but it doesn't work properly. ID just stacks too much on the same area.
Second edit: updated the code
public class Matrix
{
public int Height { get; set; }
public int Witdh { get; set; }
public int[,] Table { get; set; }
public int[,] Area { get; set; }
public int ID { get; set; }
public int tempBiggestArea = 0;
public int biggestArea { get; set; }
public Matrix(int height, int witdh)
{
Table = GenerateTable(height, witdh);
Height = height;
Witdh = witdh;
ID = 2;
Area = new int[height,witdh];
}
public int[,] GenerateTable(int height, int witdh)
{
int[,] table = new int[height, witdh];
Random rnd = new Random();
for (int i = 0; i < table.GetLength(0); i++)
{
for (int j = 0; j < table.GetLength(1); j++)
{
table[i, j] = rnd.Next(3) + 1;
}
}
return table;
}
public void Find(int x, int y, int color)
{
if (y < 0)
y = Height - 1;
if (x < 0)
x = Witdh - 1;
if (IsChanged(x, y))
return;
if (Area[x, y] == 0)
{
if (color > 3)
color = 1;
if (Table[x, y] == color)
{
Area[x, y] = ID;
tempBiggestArea++;
Find(x, y - 1, color);
Find(x - 1, y, color);
ID++;
}
}
if (tempBiggestArea > biggestArea)
biggestArea = tempBiggestArea;
tempBiggestArea = 0;
Find(x, y, color + 1);
}
public bool IsChanged(int i, int j)
{
return Area[i, j] != 0;
}

How do you create buttons on a form through a method created in a class?

I'm trying to create a grid of buttons based on what number of rows and columns the user enters and my method that creates the grid isn't working. When I call it the grid doesn't get created.
The method is inside my TileClass and I'm trying to call it in my GameBoard form. I feel like I'm not using the class properly. I don't think I'm calling the method correctly because I'm thinking this should work.
This is what the form looks like
class TileClass : Button
{
public const int LEFT = 20;
public const int WIDTH = 50;
public const int HEIGHT = 50;
public const int TOP = 50;
public const int VGAP = 30;
public int x;
public int y;
public int column;
public int row;
private int incomingRow;
private int incomingColumn;
public int IncomingRow { get => incomingRow; set => incomingRow = value; }
public int IncomingColumn { get => incomingColumn; set => incomingColumn = value; }
public TileClass()
{
}
public void CreateGrid()
{
x = LEFT;
y = TOP;
column = IncomingColumn;
row = IncomingRow;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
Button b = new Button();
b.Left = x;
b.Top = y;
b.Width = WIDTH;
b.Height = HEIGHT;
b.Text = j.ToString();
x += VGAP + HEIGHT;
this.Controls.Add(b);
}
}
}
}
Gameboard Form
public partial class GameBoard : Form
{
TileClass tileClass = new TileClass();
public GameBoard()
{
InitializeComponent();
}
private void txtEnter_Click(object sender, EventArgs e)
{
tileClass.IncomingColumn = int.Parse(txtColumn.Text);
tileClass.IncomingRow = int.Parse(txtRow.Text);
tileClass.CreateGrid();
}
There's a lot to do to make it happen:
class TileClass : Panel
{
...
public int IncomingRow {get; set;}
public int IncomingColumn { get; set; }
...
}
and remove:
private int incomingRow;
private int incomingColumn;
and the ideal approach would be using ResumeLayout before adding buttons and let the Gameboard form to be redrawn by calling Invalidate. What does invalidate method do?
note: try col=100, row=100 with and without ResumeLayout&Invalidate
public partial class GameBoard : Form
{
public GameBoard ()
{
InitializeComponent();
tileClass.Dock = DockStyle.Fill;
this.Controls.Add(tileClass);
}
TileClass tileClass = new TileClass();
private void txtEnter_Click(object sender, EventArgs e)
{
tileClass.IncomingColumn = int.Parse(txtColumn.Text);
tileClass.IncomingRow = int.Parse(txtRow.Text);
this.ResumeLayout(); //Important
tileClass.CreateGrid();
this.Invalidate(); // Important
}
}
and you can set more properties like, it needs more than this:
//tileClass.Location = new Point(10, 10); // not sure
tileClass.Dock = DockStyle.Fill;
//tileClass.Size = new Size(200, 200); // not sure
and instead of j < 5 you should use col and row:
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
Button b = new Button();
b.Left = x;
b.Top = y;
b.Width = WIDTH;
b.Height = HEIGHT;
b.Text = string.Format("({0},{1})" , i, j);
x += VGAP + HEIGHT;
this.Controls.Add(b);
}
x = LEFT; // not sure, plz calculate!
y += Top * (i+1); // not sure, plz calculate!
}

Reading an array from an XML file

At the moment iI got this:
class robot
{
Configuratie config = new Configuratie();
short[,] AlleCoordinaten = new short[3, 6]
{
{1,2,3,4,5,6},
{6,5,4,3,2,1},
{2,3,4,5,6,7}
};
}
But I want to put that array in a XML-file, so this is what I tried:
class robot
{
private static XDocument xdoc = XDocument.Load("configuratie.xml");
public Robot()
{
short[,] AlleCoordinaten = new short[3, 6];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 6; j++)
{
AlleCoordinaten[i, j] = GetPositionValue("position" + (i + 1), j);
}
}
}
public static short GetPositionValue(string position,int index)
{
return (short)xdoc.Descendants(position).Skip(index).First();
}
private void methode2()
{
GoTo[0] = new Position();
for (short a=0 ; a<10 ; a++)
{
GoTo[0].degrees[0] = AlleCoordinaten[a,0];
GoTo[0].degrees[1] = AlleCoordinaten[a,1];
GoTo[0].degrees[2] = AlleCoordinaten[a,2];
GoTo[0].degrees[3] = AlleCoordinaten[a,3];
GoTo[0].degrees[4] = AlleCoordinaten[a,4];
GoTo[0].degrees[5] = AlleCoordinaten[a,5];
//here it tells me The name 'AlleCoordinaten' does not exist in the currect context
}
}
}
configuration file:
class Configuratie
{
private XDocument xdoc;
public Configuratie()
{
xdoc = XDocument.Load("configuratie.xml");
}
public int GetIntConfig(string desc1, string desc2)
{
int value = 0;
if (string.IsNullOrEmpty(desc1))
{
value = 0;
}
if (!string.IsNullOrEmpty(desc1) && !string.IsNullOrEmpty(desc2))
{
foreach (XElement node in xdoc.Descendants(desc1).Descendants(desc2))
{
value = Convert.ToInt16(node.Value);
}
}
if (!string.IsNullOrEmpty(desc1) && string.IsNullOrEmpty(desc2))
{
foreach (XElement node in xdoc.Descendants(desc1))
{
value = Convert.ToInt16(node.Value);
}
}
return value;
}
}
XML file:
<robot>
<position1>1</position1>
<position1>2</position1>
<position1>3</position1>
<position1>4</position1>
<position1>5</position1>
<position1>6</position1>
etc...
<position3>7</position3>
</robot>
It still isnt working, could you guys help me with what I did wrong and maybe give an example.
Using XmlSerializer would simplify things by a lot:
size array automatically;
serialization/deserialization is just few rows of code.
Like this
public class Coordinate
{
public int X1 {get; set;}
public int Y1 {get; set;}
public int Z1 {get; set;}
public int X2 {get; set;}
public int Y2 {get; set;}
public int Z2 {get; set;}
public Coordinate(int x1, int y1, int z1, int x2, int y2, int z2)
{
X1 = x1; Y1 = y1; Z1 = z1; X2 = x2; Y2 = y2; Z2 = z2;
}
}
[XmlArray("Robot")]
public Coordinate[] points = new Coordinate[] {
new Coordinate(1, 2, 3, 4, 5, 6),
new Coordinate(6, 5, 4, 3, 2, 1),
new Coordinate(2, 3, 4 ,5, 6, 7),
}
// serialize (remove long namespace)
var space = new XmlSerializerNamespaces();
space.Add("", "");
var serializer = new XmlSerializer(points.GetType()); // typeof(Coordinate[])
using (var stream = new FileStream("robot.xml", FileMode.Create))
serializer.Serialize(stream, points, space);
// deserialize
using (var stream = new FileStream("robot.xml", FileMode.Open, FileAccess.Read))
points = (Coordinate[])serializer.Deserialize(stream);
Try this method:
public static short GetPositionValue(string position,int index)
{
return (short)xdoc.Descendants(position).Skip(index).First();
}
And populate your array with for loop:
Here is the full code:
class robot
{
private static XDocument xdoc = XDocument.Load("configuratie.xml");
short[,] AlleCoordinaten = new short[3, 6];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 6; j++)
{
AlleCoordinaten[i, j] = GetPositionValue("position" + (i+1), j);
}
}
public static short GetPositionValue(string position,int index)
{
return (short)xdoc.Descendants(position).Skip(index).First();
}
}
Note: CHANGE your xdoc definition:
private XDocument xdoc;
To:
private static XDocument xdoc;

Categories