I make a tetris game where i need to clear lines. I collect the full rows and make them empty by doing:
for (var i = 0; i < playingGrid.Length; i ) //get rows
{
if (!playingGrid[i].Contains(0)) //check if all colls are filled
{
playingGrid[i] = new int[10]; //make the row empty
//Here i need to push this row to the top of the jagged array
}
}
//playingGrid:
public int[][] playingGrid = new int[20][];
for (var i = 0; i < 20; i )
{
playingGrid[i] = new int[10];
}
My question is how can i get the row that i cleared at the top of the jagged array?
CodePudding user response:
You should play with indexes to move full rows. Also, no need to use int
array as the cell (column) can have only 2 states which is the perfect case for using bool
:
var rowsCount = 20;
var columnsInRowCount = 10;
var playingGrid = new bool[rowsCount][];
for (var rowIndex = 0; rowIndex < playingGrid.Length; rowIndex )
{
playingGrid[rowIndex] = new bool[columnsInRowCount];
}
var rowIndexesToMove = new List<int>(rowsCount);
var firstNonEmptyRowIndex = Array.FindIndex(playingGrid, row => row.Contains(true));
// save full row indexes (start from first non-empty one, no need to check top empty rows)
for (var rowIndex = firstNonEmptyRowIndex; rowIndex < playingGrid.Length; rowIndex )
{
var row = playingGrid[rowIndex];
if (!row.Contains(false))
{
rowIndexesToMove.Add(rowIndex);
}
}
// move full rows to top
for (var fullRowIndex = 0; fullRowIndex < rowIndexesToMove.Count; fullRowIndex )
{
for (var rowIndex = rowIndexesToMove[fullRowIndex]; rowIndex >= firstNonEmptyRowIndex fullRowIndex; rowIndex--)
{
for (var c = 0; c < playingGrid[firstNonEmptyRowIndex fullRowIndex].Length; c )
{
playingGrid[rowIndex][c] = false;
}
if (rowIndex > 0)
{
var temp = playingGrid[rowIndex];
playingGrid[rowIndex] = playingGrid[rowIndex - 1];
playingGrid[rowIndex - 1] = temp;
}
}
}