I'm creating simple game which board is based on Grid layout. I make f.e. 20rows x 20columns grid, some of them are filled by some FrameworkElement. I want to make drag&drop mechanism for them and I wonder how to find row&column of grid by mouse position.
Any idea?
Ok i found such function:
public Cell GetCell(Point position)
{
Cell cell = new Cell();
cell.Column = -1;
double total = 0;
foreach (var column in boardGrid.ColumnDefinitions)
{
if(position.X < total)
{
break;
}
cell.Column++;
total += column.ActualWidth;
}
cell.Row = -1;
total = 0;
foreach (var row in boardGrid.RowDefinitions)
{
if(position.Y < total)
{
break;
}
cell.Row++;
total += row.ActualHeight;
}
return cell;
}
Related
I want to disable rows autoscaling of TableLayoutPanel so that it would fit, for example, 4 columns on width and 3 rows on height and autoscrolling also would work. What should I change?
Code:
public UserControl()
{
InitializeComponent();
tableLayoutPanel1.ColumnStyles.Clear();
tableLayoutPanel1.RowStyles.Clear();
foreach (Picture picture in Program.gallery)
addImage(picture);
for (int i=0;i<tableLayoutPanel1.ColumnCount;i++)
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100f/4));
for (int i = 0; i < 99999; i++)
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 100f/3));
}
TableLayoutPanel has:
AutoScroll=true;
AutoSize=false;
ColumnCount=4;
RowCount=3;
Dock=true;
GrowStyle=AddRows;
Percent size type is broken.
Scrollbar of TableLayoutPanel is also glitchy and is not shrink. Here
I used these properites for table:
AutoScroll=false;
AutoSize=true;
ColumnCount=4;
RowCount=0;
Dock=Top;
GrowStyle=AddRows;
and external control property:
AutoScroll=true;
Code for checking rows count and disabling unused:
private int cellsCount=0;
private const int rows = 3;
private int CellsCount {
get => cellsCount;
set {
cellsCount = value;
int expectedRows = (cellsCount - 1 + tableLayoutPanel1.ColumnCount) / tableLayoutPanel1.ColumnCount;
while (expectedRows > tableLayoutPanel1.RowCount)
{
tableLayoutPanel1.RowCount++;
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Absolute, Height/rows));
}
while (expectedRows < tableLayoutPanel1.RowCount) {
tableLayoutPanel1.RowCount--;
tableLayoutPanel1.RowStyles.RemoveAt(0);
}
}
}
And resize listener to set true dimensions of rows:
private void tableLayoutPanel1_Resize(object sender, EventArgs e)
{
foreach (RowStyle row in tableLayoutPanel1.RowStyles)
row.Height = Height / rows;
}
I'm developing a theatre reservation software. I'm using Windows Forms, the seats is represented by a 2-dimensioned array. And I draw the buttons as following:
public void DrawSeats()
{
// pnl_seats is a Panel
pnl_seats.Controls.Clear();
// Here I store all Buttons instance, to later add all buttons in one call (AddRange) to the Panel
var btns = new List<Control>();
// Suspend layout to avoid undesired Redraw/Refresh
this.SuspendLayout();
for (int y = 0; y < _seatZone.VerticalSize; y++)
{
for (int x = 0; x < _seatZone.HorizontalSize; x++)
{
// Check if this seat exists
if (IsException(x, y))
continue;
// Construct the button with desired properties. SeatSize is a common value for every button
var btn = new Button
{
Width = SeatSize,
Height = SeatSize,
Left = (x * SeatSize),
Top = (y * SeatSize),
Text = y + "" + x,
Tag = y + ";" + x, // When the button clicks, the purpose of this is to remember which seat this button is.
Font = new Font(new FontFamily("Microsoft Sans Serif"), 6.5f)
};
// Check if it is already reserved
if (ExistsReservation(x, y))
btn.Enabled = false;
else
btn.Click += btn_seat_Click; // Add click event
btns.Add(btn);
}
}
// As said before, add all buttons in one call
pnl_seats.Controls.AddRange(btns.ToArray());
// Resume the layout
this.ResumeLayout();
}
But already with a seat zone of 20 by 20 (400 buttons), it spent almost 1 minute to draw it, and in debug I checked that the lack of performance, is the instantiation of the buttons.
There is a way to make it faster? Perhaps disable all events during the instatiation or another lightweight Control that has the Click event too?
UPDATE:
lbl was a test, the correct is btn, sorry.
UPDATE 2:
Here is the IsException and ExistsReservations methods:
private bool IsException(int x, int y)
{
for (var k = 0; k < _seatsExceptions.GetLength(0); k++)
if (_seatsExceptions[k, 0] == x && _seatsExceptions[k, 1] == y)
return true;
return false;
}
private bool ExistsReservation(int x, int y)
{
for (var k = 0; k < _seatsReservations.GetLength(0); k++)
if (_seatsReservations[k, 0] == x && _seatsReservations[k, 1] == y)
return true;
return false;
}
Suppose that you change your arrays for reservations and exclusions to
public List<string> _seatsExceptions = new List<string>();
public List<string> _seatsReservations = new List<string>();
you add your exclusions and reservations in the list with something like
_seatsExceptions.Add("1;10");
_seatsExceptions.Add("4;19");
_seatsReservations.Add("2;5");
_seatsReservations.Add("5;5");
your checks for exclusions and reservations could be changed to
bool IsException(int x, int y)
{
string key = x.ToString() + ";" + y.ToString();
return _seatsExceptions.Contains(key);
}
bool ExistsReservation(int x, int y)
{
string key = x.ToString() + ";" + y.ToString();
return _seatsReservations.Contains(key);
}
of course I don't know if you are able to make this change or not in your program. However consider to change the search on your array sooner or later.
EDIT I have made some tests, and while a virtual grid of 20x20 buttons works acceptably well (31 millisecs 0.775ms on average), a bigger one slows down noticeably. At 200x50 the timing jumps to 10 seconds (1,0675 on average). So perhaps a different approach is needed. A bound DataGridView could be a simpler solution and will be relatively easy to handle.
I also won't use such a myriad of controls to implement such a thing. Instead you should maybe create your own UserControl, which will paint all the seats as images and reacts on a click event.
To make it a little easier for you i created such a simple UserControl, that will draw all the seats and reacts on a mouse click for changing of the state. Here it is:
public enum SeatState
{
Empty,
Selected,
Full
}
public partial class Seats : UserControl
{
private int _Columns;
private int _Rows;
private List<List<SeatState>> _SeatStates;
public Seats()
{
InitializeComponent();
this.DoubleBuffered = true;
_SeatStates = new List<List<SeatState>>();
_Rows = 40;
_Columns = 40;
ReDimSeatStates();
MouseUp += OnMouseUp;
Paint += OnPaint;
Resize += OnResize;
}
public int Columns
{
get { return _Columns; }
set
{
_Columns = Math.Min(1, value);
ReDimSeatStates();
}
}
public int Rows
{
get { return _Rows; }
set
{
_Rows = Math.Min(1, value);
ReDimSeatStates();
}
}
private Image GetPictureForSeat(int row, int column)
{
var seatState = _SeatStates[row][column];
switch (seatState)
{
case SeatState.Empty:
return Properties.Resources.emptySeat;
case SeatState.Selected:
return Properties.Resources.choosenSeat;
default:
case SeatState.Full:
return Properties.Resources.fullSeat;
}
}
private void OnMouseUp(object sender, MouseEventArgs e)
{
var heightPerSeat = Height / (float)Rows;
var widthPerSeat = Width / (float)Columns;
var row = (int)(e.X / widthPerSeat);
var column = (int)(e.Y / heightPerSeat);
var seatState = _SeatStates[row][column];
switch (seatState)
{
case SeatState.Empty:
_SeatStates[row][column] = SeatState.Selected;
break;
case SeatState.Selected:
_SeatStates[row][column] = SeatState.Empty;
break;
}
Invalidate();
}
private void OnPaint(object sender, PaintEventArgs e)
{
var heightPerSeat = Height / (float)Rows;
var widthPerSeat = Width / (float)Columns;
e.Graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
e.Graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
for (int row = 0; row < Rows; row++)
{
for (int column = 0; column < Columns; column++)
{
var seatImage = GetPictureForSeat(row, column);
e.Graphics.DrawImage(seatImage, row * widthPerSeat, column * heightPerSeat, widthPerSeat, heightPerSeat);
}
}
}
private void OnResize(object sender, System.EventArgs e)
{
Invalidate();
}
private void ReDimSeatStates()
{
while (_SeatStates.Count < Rows)
_SeatStates.Add(new List<SeatState>());
if (_SeatStates.First().Count < Columns)
foreach (var columnList in _SeatStates)
while (columnList.Count < Columns)
columnList.Add(SeatState.Empty);
while (_SeatStates.Count > Rows)
_SeatStates.RemoveAt(_SeatStates.Count - 1);
if (_SeatStates.First().Count > Columns)
foreach (var columnList in _SeatStates)
while (columnList.Count > Columns)
columnList.RemoveAt(columnList.Count - 1);
}
}
This will currently draw forty rows and columns (so there are 800 seats) and you can click on each seat to change its state.
Here are the images i used:
EmtpySeat:
ChoosenSeat:
FullSeat:
If you anchor this control and resize it or you click on a seat to change its state there can be some minor lacking for the repainting if you further increase the number of rows or columns, but that is still somewhere far below one second. If this still hurts you, you have to improve the paint method and maybe check the ClipRectangle property of the paint event and only paint the really needed parts, but that's another story.
Rather than using actual button controls, just draw the image of the seats then when the user clicks on a seat translate the mouse X,Y coordinates to determine which seat was clicked. This will be more efficient. Of course, the drawback is that you have to write the method to translate x,y coordinates to a seat, but that really isn't that difficult.
EDIT; it has been pointed out to me this will not work in Windows Forms!
Well, you are Sequentially working through it.
if one iteration costs 1 sec, the full process will take 400*1 in time.
Perhaps you should try and make a collection of your objects, and process it 'parallel'.
try the .Net framework (4 and above) 'parallel foreach' method:
http://msdn.microsoft.com/en-s/library/system.threading.tasks.parallel.foreach(v=vs.110).aspx
edit: so, if you have a list buttonnames, you can say
buttonNames.ForEach(x=>CreateButton(x));
while your CreateButton() method is as following:
private Button CreateButton(string nameOfButton) { Button b = new
Button(); b.Text = nameOfButton; //do whatever you want...
return b; }
How can I get the value of the cell index where the user has clicked in tablelayoutpanel.
I want to get the value of column and row and then show it in messagebox.
How can i achieve this using c# ?
You can get the location like this:
private void tableLayoutPanel1_MouseClick(object sender, MouseEventArgs e)
{
int row = 0;
int verticalOffset = 0;
foreach (int h in tableLayoutPanel1.GetRowHeights())
{
int column = 0;
int horizontalOffset = 0;
foreach(int w in tableLayoutPanel1.GetColumnWidths())
{
Rectangle rectangle = new Rectangle(horizontalOffset, verticalOffset, w, h);
if(rectangle.Contains(e.Location))
{
Trace.WriteLine(String.Format("row {0}, column {1} was clicked", row, column));
return;
}
horizontalOffset += w;
column++;
}
verticalOffset += h;
row++;
}
}
i need help on a maze game that i'm trying to build. I know there is a lot written on that topic, but i can't get it right. So, on the problem - i want the user to escape from the maze with arrow keys. I build the maze from 2-d array of rectangle cells from the tutorial here.
And that is the method.
public static Grid DFS(Grid grid)
{
Stack<Cell> cellStack = new Stack<Cell>();
int totalCells = grid.Cells.GetLength(0) * grid.Cells.GetLength(1);
Cell currentCell = grid.Cells[0, 0];
currentCell.IsVisited = true;
grid.VisitedCells = 1;
while (grid.VisitedCells < totalCells)
{
List<Cell> neighbours = GetNeighbours(grid, currentCell);
if (neighbours.Count > 0)
{
Cell newCell = GetRandomNeighbour(neighbours);
CrushWall(currentCell, newCell);
newCell.IsVisited = true;
cellStack.Push(currentCell);
currentCell = newCell;
grid.VisitedCells++;
}
else
{
currentCell = cellStack.Pop();
}
}
return grid;
}
Then i add it on a panel in the main form:
private void mediumToolStripMenuItem_Click(object sender, EventArgs e)
{
panel1.Controls.Clear();
Grid grid = new Grid(30, 30);
panel1.Size = grid.Size;
grid.BorderStyle = BorderStyle.FixedSingle;
panel1.Controls.Add(grid);
maze = Maze.DFS(grid);
}
So far so good. Now i want to escape from the maze. Start point is Cell[0,0] and the goal is at the last Cell, let's say Cell[30,30]. Here is my attempt for that. It's not finished yet and covers just when we go right and down. What it happens is that i go just one cell right or down and that's it. Noting more! Please tell me where i'm wrong!
void frmMain_KeyDown(object sender, KeyEventArgs e)
{
for (int i = 0; i < maze.Rows; i++)
{
for (int j = 0; j < maze.Columns; j++)
{
maze.Cells[i, j].IsVisited = false;
}
}
Cell currentCell = maze.Cells[0, 0];
if (currentCell == maze.Cells[maze.Rows - 1, maze.Columns - 1])
{
MessageBox.Show("Well Done! You made it!");
}
else
{
switch (e.KeyCode)
{
case Keys.Right:
currentCell = Maze.GoRight(maze, currentCell);
currentCell.IsOnPath = true;
maze.Invalidate();
break;
case Keys.Down:
currentCell = Maze.GoDown(maze, currentCell);
currentCell.IsOnPath = true;
maze.Invalidate();
break;
}
}
}
And here is the going right for example:
public static Cell GoRight(Grid maze, Cell currentCell)
{
List<Cell> neighbours = GetMazeNeighbours(maze, currentCell);
Cell rightNeighbour = new Cell();
if (neighbours.Any())
{
foreach (var item in neighbours)
{
if (item.LeftWall == 1)
{
rightNeighbour = item;
}
}
}
return rightNeighbour;
}
Two potential problems I can see straight away. Firstly, most seriously, you're initialising currentCell to the cell at [0,0] every time you press a key. So, every time a key is pressed currentCell goes back to [0,0]! That can't be right.
Secondly, you need to break out or return from your foreach as soon as you assign rightNeighbour, or any other cells in the list of neighbours that are subsequently found matching the item.LeftWall == 1 criteria will overwrite the assignment.(Plus it's inefficient to iterate through a list when you've already found what you're looking for).
e.g.
foreach (var item in neighbours)
{
if (item.LeftWall == 1)
{
rightNeighbour = item;
break;
}
}
Finally i was able to locate the problem and fix it. Here it is on the image:
The black cell is the current cell that we`re on. The yellow ones are the neighbours. The problem is that the two neighbours have the same properties. For example:
neighbour1.TopWall = 1;
neighbour2.TopWall = 1;
This means that the top wall of both neighbours is crushed.
Let`s say i want to go down. In the KeyDown event the condition for going down is true for both of the neighbours, so it is pure luck that the correct neighbour is the first met here:
foreach (var item in neighbours)
{
if (item.TopWall == 1)
{
rightNeighbour = item;
break;
}
}
And i solved it like this:
if current cell has neighbours
check if bottom cell is not null
if false, check if its top wall is crushed
if true, make bottom cell the current cell
I hope this will help to someone! Cheers!
When i drag one picturebox, it drags both of mine. Because in the pbxMap_DragDrop method i have to call both of the methods that should fire when i drag one.
private void pbxMap_DragDrop(object sender, DragEventArgs e)
{
myDetectMouse.setMinotaur(e, myMap.myCells);
myDetectMouse.setTheseus(e, myMap.myCells);
}
SetTheseus:
public void setTheseus(DragEventArgs e, List<Cell> cells)
{
for (int i = 0; i < cells.Count; i++)
{
int[] mapData = myMapController.getMapData(i, cells);
int column = mapData[0];
int row = mapData[1];
int right = mapData[2];
int bottom = mapData[3];
Point RelativeMouseLoc = myMapController.myMap.myForm.pbxMap.PointToClient(Cursor.Position);
if (RelativeMouseLoc.X > column &&
RelativeMouseLoc.X < column + myMapController.myMap.myCellSize
&& RelativeMouseLoc.Y > row && RelativeMouseLoc.Y <
row + myMapController.myMap.myCellSize)
{
myMapController.myMap.myCells[i].hasTheseus = true;
}
else
{
myMapController.myMap.myCells[i].hasTheseus = false;
}
}
}
SetMinotaur is much the same but replace hasTheseus with hasMinotaur. As soon as a cell "hasTheseus" or "hasMinotaur" it will be drawn to the cell.
So it draws them both when i drag one because they both get set in pbxMap_DragDrop.
I thought i could have multiple event handlers for pbxMap_DragDrop depending on which picturebox was dragged.
You can check the sender parameter to determine whether you want to move the minotaur or Theseus. It would look something like this:
var pic = (PictureBox)sender;
if (pic.Name == "minotaur")
{
myDetectMouse.setMinotaur(e, myMap.myCells);
}
else
{
myDetectMouse.setTheseus(e, myMap.myCells);
}
If you don't want to use the Name property, you can use something else like the Tag property - just make sure you set it for each of the PictureBox objects.