I am doing a 15 puzzle game on wpf and xaml where you need to move the empty tile in a grid to solve the puzzle. (see the linked image for context) I want to know how I can go about changing a button's coordinates when switching it with the coordinates of the empty tile using the up,down,left,right buttons. Here below you have an example of the coordinates i am talking about, .row and .column.
<Button x:Name="Button10" Grid.Column="1" Grid.Row="0" Content="3"/>```
CodePudding user response:
You can change the Row or Column of your Buttons like this.
// Move up Button5 example
private void ButtonUp_Click(object sender, RoutedEventArgs e)
{
// Get the current Row
int currentRow = Grid.GetRow(Button5);
// Calculate the next Row
int nextRow = Math.Min(Math.Max(currentRow - 1, 0), 3);
// Change the Row
Grid.SetRow(Button5, nextRow);
}
// Move left Button5 example
private void ButtonLeft_Click(object sender, RoutedEventArgs e)
{
// Get the current Column
int currentColumn = Grid.GetColumn(Button5);
// Calculate the next Column
int nextColumn = Math.Min(Math.Max(currentColumn - 1, 0), 3);
// Change the Column
Grid.SetColumn(Button5, nextColumn);
}
CodePudding user response:
You can obtain the position of an element by calling it as part of the Grid.GetRow
or Grid.GetColumn
methods.
int row = Grid.GetRow(button1);
int column = Grid.GetColumn(button1);
It might be best to create an object type for this so you can keep track of many buttons and what their positions were even after they moved.
public class position
{
private int row;
private int column;
public position(int row, int column)
{
this.Row = row;
this.Column = column;
}
public int Row
{
get => row;
set => row = value;
}
public int Column
{
get => column;
set => column = value;
}
}
and then you can mark the current position of multiple grid items
position first_button = new position(Grid.GetRow(button1), Grid.GetColumn(button1));
position second_button = new position(Grid.GetRow(button2), Grid.GetColumn(button2));
and from there you can call these objects to move grid elements
Grid.SetColumn(button2, first_button.Column);
Grid.SetRow(button2, first_button.Row);