Function is not updating Button.Text c# - c#

I have a grid of buttons that should reveal some info when they are clicked (within the button itself) For a knowledge assignment I'm trying to program minesweeper.
The grid method:
public void createGrid()
{
for (int i = 0; i < 8; i++)
{
grid[i] = new Cell[8];
for (int j = 0; j < 8; j++)
{
chance = rand1.Next(0, 6);
if (chance == 0 && bombAmount < 10)
{
grid[i][j] = new Cell(true);
bombAmount++;
}
else
{
grid[i][j] = new Cell();
}
grid[i][j].Name = "grid" + i.ToString() + j.ToString();
grid[i][j].Location = new System.Drawing.Point(i * 49, j * 49);
grid[i][j].Size = new System.Drawing.Size(50, 50);
grid[i][j].TabIndex = 0;
grid[i][j].Font = new System.Drawing.Font("Microsoft Sans Serif", 26.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
}
}
for (int i = 0; i < 8; i++)
{
for (int j = 0; j <8; j++)
{
this.Controls.Add(grid[i][j]);
}
}
}
The Reveal method:
public void RevealCell(int n, int m)
{
if (grid[n][m].HasBomb == true)
{
grid[n][m].Text = "B";
}
else if (grid[n][m].NeighbourBombCount > 0)
{
grid[n][m].Text = grid[n][m].NeighbourBombCount.ToString();
}
else
{
grid[n][m].Text = "NB";
}
grid[n][m].IsRevealed = true;
}
and then there's the checking if neighbours have bombs or not method:
public void CheckNeighbours(int cswitch)
{
switch (cswitch)
{
// Left upper corner (i = 0, j = 0)
case 1:
for (int i = 0; i <= 1; i++)
{
for (int j = 0; j < 1; j++)
{
if (i == 0 && j == 0) { }
else
{
if (grid[i][j].HasBomb == true)
{
grid[0][0].NeighbourBombCount++;
}
}
}
}
break;
// Upper edge (i = 0, 0 < j < 7)
case 2:
for (int i = 0; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
if (i == 0 && j == 0) { }
else
{
if (grid[i][j].HasBomb == true)
{
grid[0][0].NeighbourBombCount++;
}
}
}
}
break;
// Right upper corner (i = 0, j = 7)
case 3:
for (int i = 0; i <= 1; i++)
{
for (int j = -1; j <= 0; j++)
{
if (i == 0 && j == 0) { }
else
{
if (grid[i][j].HasBomb == true)
{
grid[0][0].NeighbourBombCount++;
}
}
}
}
break;
// Right edge (0 < i < 7, j = 7)
case 4:
for (int i = -1; i <= 1; i++)
{
for (int j = -1; j <= 0; j++)
{
if (i == 0 && j == 0) { }
else
{
if (grid[i][j].HasBomb == true)
{
grid[0][0].NeighbourBombCount++;
}
}
}
}
break;
// Right down corner (i = 7, j = 7)
case 5:
for (int i = -1; i <= 0; i++)
{
for (int j = -1; j <= 0; j++)
{
if (i == 0 && j == 0) { }
else
{
if (grid[i][j].HasBomb == true)
{
grid[0][0].NeighbourBombCount++;
}
}
}
}
break;
// Bottom edge (i = 7, 0 < j < 7)
case 6:
for (int i = -1; i <= 0; i++)
{
for (int j = -1; j <= 1; j++)
{
if (i == 0 && j == 0) { }
else
{
if (grid[i][j].HasBomb == true)
{
grid[0][0].NeighbourBombCount++;
}
}
}
}
break;
// Left down corner (i = 7, j = 0)
case 7:
for (int i = -1; i <= 0; i++)
{
for (int j = -1; j <= 1; j++)
{
if (i == 0 && j == 0) { }
else
{
if (grid[i][j].HasBomb == true)
{
grid[0][0].NeighbourBombCount++;
}
}
}
}
break;
// Left edge (i = 0, 0 < j < 7)
case 8:
for (int i = 0; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
if (i == 0 && j == 0) { }
else
{
if (grid[i][j].HasBomb == true)
{
grid[0][0].NeighbourBombCount++;
}
}
}
}
break;
default:
for (int i = -1; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
if (i == 0 && j == 0) { }
else
{
if (grid[i][j].HasBomb == true)
{
grid[0][0].NeighbourBombCount++;
}
}
}
}
break;
}
}
As my buttons are laid out in grid fashion the Top left button is button 1 and right bottom button is button 64 (hence the switch statements).
Edit: Didn't add the Click method to the grid[i][j].Click += handler...
Update:
private void Cell_click(object sender, EventArgs e)
{
e.
if(i == 0 && j == 0)
{
CheckNeighbours(1);
}
if (i == 0 && j > 0 && j < 7)
{
CheckNeighbours(2);
}
if (i == 0 && j == 7)
{
CheckNeighbours(3);
}
if (i > 0 && i < 7 && j == 7)
{
CheckNeighbours(4);
}
if (i == 7 && j == 7)
{
CheckNeighbours(5);
}
if (i == 7 && j > 0 && j < 7)
{
CheckNeighbours(6);
}
if (i == 7 && j == 0)
{
CheckNeighbours(7);
}
if(i > 0 && i < 7 && j == 0)
{
CheckNeighbours(8);
}
RevealCell(i, j);
}
Now I just need to know how to grab the i and j indeces from the sender object and I'm golden!

you need
cell[i][j].Click += new System.EventHandler(this.CellClick);
and create a single CellClick event handler method

Related

MiniMax algorithm for 4 in a row

I'm trying to implement minimax algorithm, but it isn't working, the computer is just making moves randomly. Here is the method Minimax and ComputerLogic.
static int MiniMax(int[,] board, int depth, bool isMax)
{
int len = 0;
for (int i = 0; i < board.GetLength(0); i++)
{
for (int j = 0; j < board.GetLength(1); j++)
{
if (board[i, j] == 0) len++;
}
}
int best_score, score;
if (WinVariants(board, 1))
{
best_score = -10;
return best_score;
}
else if (WinVariants(board, 2))
{
best_score = 10;
return best_score;
}
else if (len == 0)
{
best_score = 0;
return best_score;
}
if (isMax)
{
best_score = -int.MaxValue;
for (int i = 0; i < board.GetLength(0); i++)
{
for (int j = 0; j < board.GetLength(1); j++)
{
if (board[i, j] == 0)
{
board[i, j] = 1;
score = MiniMax(board, depth + 1, false);
board[i, j] = 0;
best_score = Math.Max(best_score, score);
}
}
}
}
else
{
best_score = int.MaxValue;
for (int i = 0; i < board.GetLength(0); i++)
{
for (int j = 0; j < board.GetLength(1); j++)
{
if (board[i, j] == 0)
{
board[i, j] = 2;
score = MiniMax(board, depth + 1, true);
board[i, j] = 0;
best_score = Math.Min(best_score, score);
}
}
}
}
return best_score;
}
static void ComputerLogic(int[,] grid, int VariantMove)
{
int[,] board = Copy(grid);
int bestScore = -int.MaxValue, score;
int len = 0;
Random rnd = new Random();
if (len <= 2)
{
while (true)
{
int x = rnd.Next(0, 7);
int y = rnd.Next(0, 7);
len++;
if (grid[x, y] == 0)
{
grid[x, y] = 1;
break;
}
}
}
else
{
while (true)
{
for (int i = 0; i < board.GetLength(0); i++)
{
for (int j = 0; j < board.GetLength(1); j++)
{
if (board[i, j] == 0)
{
board[i, j] = 1;
score = MiniMax(board, 0, false);
board[i, j] = 0;
if (score > bestScore)
{
bestScore = score;
grid[i, j] = 1;
break;
}
}
}
}
}
}
}
Too, i have method for Drawing my grid view 2d array.
If I choose the PC to go first, then it goes randomly. Otherwise, my mesh just isn't drawing.
I am guessing that I am not filling my main grid array correctly. Its copy is used for verification - board.
Can please help me with this problem?

Array index out of bounds when making it check the list in reverse

so after my previous issue got fixed i went to add some more code and i'v been trying looking on here and other places i cant find anything that explains my issue so is there a way to make this code
for (int j = 0; j < 4; j++) {
worldX = 0;
worldY = 0;
while (worldY != WorldHeight) {
while (worldX != WorldWidth) {
if (worldY > 0) {
if (worldX > 0) {
if (world[worldX-1, worldY-1] == 1 && genran.Next(genran.Next(genran.Next(-7,-1),genran.Next(0,2)),genran.Next(genran.Next(5,8),genran.Next(9,16))) > 6) { world[worldX, worldY] = 1;}
} if ((worldX + 1) < WorldWidth) {
if (world[worldX+1, worldY-1] == 1 && genran.Next(genran.Next(genran.Next(-7,-1),genran.Next(0,2)),genran.Next(genran.Next(5,8),genran.Next(9,16))) > 6) { world[worldX, worldY] = 1;}
}
}
worldX++;
}
worldX = 0;
worldY++;
}
}
into something like this
for (int j = 0; j < 4; j++) {
worldX = WorldWidth;
worldY = WorldHeight;
while (worldY >= 0) {
while (worldX >= 0) {
if (worldY > 0) {
if (worldX > 0) {
if (world[worldX-1, worldY-1] == 1 && genran.Next(genran.Next(genran.Next(-7,-1),genran.Next(0,2)),genran.Next(genran.Next(5,8),genran.Next(9,16))) > 6) { world[worldX, worldY] = 1;}
} if ((worldX - 1) > 0) {
if (world[worldX+1, worldY-1] == 1 && genran.Next(genran.Next(genran.Next(-7,-1),genran.Next(0,2)),genran.Next(genran.Next(5,8),genran.Next(9,16))) > 6) { world[worldX, worldY] = 1;}
}
}
worldX--;
}
worldX = WorldWidth;
worldY--;
}
}
so instead of starting at the top left i want to start at the bottom right an go backwards from there
PS. I'm still new to some of this.

AI does not play well in vertical tic tac toe c#

I'm doing a tic tac toe game with an AI. The AI plays well, except when it has to win with a vertical. All the other ways (horizontal and diagonal) does work.
I've done a lot of debugging and step by step and haven't found the solution. I thought you guys could help me finding the problem and help me solving it!
int findTwoPions(Boolean?[,] jeu)
{
// La méthode qui selon moi est à modifier car c'est celle ci qui décide la position que doit prendre l'IA quand elle peu gagner
int somme = 0;
int compteurX = 0;
int compteur0 = 0;
//Diagonale descendante
for (int i = 0; i < 3; i++)
{
if ((jeu[0, 0] == false || jeu[1, 1] == false || jeu[2, 2] == false) && (jeu[0, 0] == true || jeu[1, 1] == true || jeu[2, 2] == true))
{
somme += 0;
}
else
{
if (jeu[i, i] == false)
{
compteur0++;
compteurX = 0;
if (compteur0 == 2)
{
somme += 1500;
}
}
else if (jeu[i, i] == true)
{
compteur0 = 0;
compteurX++;
if (compteurX == 2)
{
somme -= 1600;
}
}
}
}
compteurX = 0;
compteur0 = 0;
//Diagonale montante
for (int i = 0; i < 3; i++)
{
if ((jeu[0, 2] == false || jeu[1, 1] == false || jeu[2, 0] == false) && (jeu[0, 2] == true || jeu[1, 1] == true || jeu[2, 0] == true))
{
}
else
{
if (jeu[i, 2 - i] == false)
{
compteur0++;
compteurX = 0;
if (compteur0 == 2)
{
somme += 1500;
}
}
else if (jeu[i, 2 - i] == true)
{
compteurX++;
compteur0 = 0;
if (compteurX == 2)
{
somme -= 1600;
}
}
}
}
//En ligne
for (int i = 0; i < 3; i++)
{
compteurX = 0;
compteur0 = 0;
if ((jeu[0, i] == false || jeu[1, i] == false || jeu[2, i] == false) && (jeu[0, i] == true || jeu[1, i] == true || jeu[2, i] == true))
{
somme += 0;
}
else
{
//Verticale
for (int j = 0; j < 3; j++)
{
if (jeu[j, i] == false)
{
compteur0++;
compteurX = 0;
if (compteur0 == 2)
{
somme += 1500;
}
}
else if (jeu[j, i] == true)
{
compteurX++;
compteur0 = 0;
if (compteurX == 2)
{
somme -= 1600;
}
}
}
}
compteurX = 0;
compteur0 = 0;
if ((jeu[i, 0] == false || jeu[i, 1] == false || jeu[i, 2] == false) && (jeu[i, 0] == true || jeu[i, 1] == true || jeu[i, 2] == true))
{
return somme += 0;
} // Voir les valeurs i j pcque c'est faux
else
{
//Horizontale
for (int j = 0; j < 3; j++)
{
if (jeu[i, j] == false)
{
compteur0++;
compteurX = 0;
if (compteur0 == 2)
{
somme += 1500;
}
}
else if (jeu[i, j] == true)
{
compteurX++;
compteur0 = 0;
if (compteurX == 2)
{
somme -= 1600;
}
}
}
}
}
return somme;
}
}
}
I think the problem is when I add a value to 'somme' or the way I run trough my tic tac toe.
If you need further code please tell me, thank you !
UPDATE:
MY AIRoutine.cs
public Boolean?[][] IAPlay(Boolean?[][] jeu, int profondeur)
{
int max = -10000;
int tmp, tmp2 = 0, tmpSomme = -10000; // -10000
int tmpBefore = 0;
int maxi = 0, maxj = 0;
int somme = 0;
int biggestSomme = 0;
setTab(jeu); // convertit le tableau[][] en tableau[,]
for (int i = 0; i < 3; i++) // parcours toutes les cases vides du tableau
{
for (int j = 0; j < 3; j++)
{
//Si une case est vide, on joue le coup de l'IA sur cette case et on simule le jeu complet
if (tab[i, j] == null)
{
tab[i, j] = false; // On simule le coup de l'IA
somme = findTwoPions(tab);
tmp = Max(tab, profondeur - 1);
if (tmpBefore < tmp && biggestSomme > somme)
{
tmpSomme = somme + tmpBefore;
}
else if (tmpBefore > tmp && biggestSomme < somme)
{
tmpSomme = somme + tmpBefore;
}
else
{
tmpSomme = tmp + somme;
}
if (somme > biggestSomme)
{
biggestSomme = somme;
tmpBefore = tmp;
}
//|| ((tmp == max) && (r.Next(1, 100) % 2 == 0))
if (tmpSomme >= max)
{
max = tmpSomme;
tmp2 = somme;
maxi = i;
maxj = j;
}
tab[i, j] = null;
}
}
}
tab[maxi, maxj] = false;
return getTab(jeu);
}
Let's put it in readable and maintainabe way: let's extract a method WinningLines where we enumerate all winning combinations (I've assummed that jue is 2d array - bool?[3, 3]):
using System.Linq;
...
private static IEnumerable<bool?[]> WinningLines(bool?[,] field) {
// Verticals
for (int column = 0; column < 3; ++column)
yield return new bool?[] {field[0, column], field[1, column], field[2, column]};
// Horizontals
for (int row = 0; row < 3; ++row)
yield return new bool?[] {field[row, 0], field[row, 1], field[row, 2]};
// Diagonals
yield return new bool?[] {field[0, 0], field[1, 1], field[2, 2]};
yield return new bool?[] {field[0, 2], field[1, 1], field[2, 0]};
}
Now let's query (with a help of Linq):
// Do we have any winning combinations for the 1st Player (all 3 true in WinningLines):
bool hasFirstWon = WinningLines(jeu).Any(line => line.All(cell => cell == true));
// Do we have any winning combinations for the 2nd Player (all 3 false in WinningLines):
bool hasSecondWon = WinningLines(jeu).Any(line => line.All(cell => cell == false));
Or if you operate with somme:
int somme =
WinningLines(jeu).Any(line => line.All(cell => cell == true)) ?
1500 // 1st wins
: WinningLines(jeu).Any(line => line.All(cell => cell == false)) ?
-1600 // 2nd wins
: 0; // no-one wins
Edit: Now let's implement a (simple) version of the int findTwoPions(Boolean?[,] jeu) method. First let's have
private static bool FirstIsOnMove(bool?[,] field) {
int count = 0;
foreach (var item in field)
if (item == true)
count += 1;
else if (item == true)
count -= 1;
return count == 0;
}
and the method itself will be
// This method rates the position in a [-1600..1500] range
// [1st player has lost..1st player has won]
int findTwoPions(Boolean?[,] jeu) {
// Edge cases: win or lose
if (WinningLines(jeu).Any(line => line.All(cell => cell == true)))
return 1500; // 1st has won
else if (WinningLines(jeu).Any(line => line.All(cell => cell == false)))
return -1600; // 1st has lost
//TODO: add more heuristics (depending who is on move)
// Example: if palayer is on move and can win by its next move?
// Say, we have positions like
// X.. XXO
// OX. Or X.O
// .O. ...
if (FirstIsOnMove(jeu)) {
if (WinningLines(jeu)
.Any(line => line.Sum(item => item == true ? 1 : item == false ? -1 : 0) == 2))
return 1200; // 1st is going to win (unless it makes a blind)
}
else {
if (WinningLines(jeu)
.Any(line => line.Sum(item => item == true ? 1 : item == false ? -1 : 0) == -2))
return -1200; // 2st is going to win (unless it makes a blind)
}
// Neutral position - neither 1st not 2nd have any advantages
return 0;
}

Counting Sort Implementation in C#

I am implementing counting sort But some thing is wrong with my code
I am new in Programming Please help me to find an error.
I am implenting it step by step .
namespace ConsoleApplication1
{
class Program
{
public static int[] a = { 0,0,0,5,4,8,9,9,7,3, 3, 2, 1 };
public static void Sorting()
{
int j = 0, i = 0, smallestvalue = 0, largestvalue = 0, n = a.Length, lengthof_B = 0, temp = 0, anothersmallestvalue;
smallestvalue = largestvalue = a[0];
for (i = 0; i < n; i++)
{
if (smallestvalue > a[i])
{
smallestvalue = a[i];
}
else if (largestvalue < a[i])
{
largestvalue = a[i];
}
}
int x = anothersmallestvalue = smallestvalue;
lengthof_B = largestvalue - smallestvalue + 1;
int[] b = new int[lengthof_B];
for (i = 0; i < lengthof_B && smallestvalue <= largestvalue; i++)
{
for (j = 0; j < n; j++)
{
if (smallestvalue == a[j])
{
b[i] = b[i] + 1;
}
}
b[i] = temp + b[i];
temp = b[i];
smallestvalue++;
}
int[] c = new int[a.Length];
// I think error here
for (i = n - 1; i >= 0; i--)
{
anothersmallestvalue = x;
for (j = 0; j <= lengthof_B ; j++)
{
if (a[i] == anothersmallestvalue)
{
temp = b[j];
c[temp - 1] = anothersmallestvalue;
b[j] = b[j];
}
anothersmallestvalue++;
}
}
for (i = 0; i < c.Length; i++)
{
Console.WriteLine("c[i] : " + c[i]);
}
}
}
class Demo
{
static void Main(string[] args)
{
Program.Sorting();
Console.ReadLine();
}
}
}
Desired Output is
000123457899
But output of my program is
000120457809
This Is Your Code Here I found a mistake.
And your Code is too complex Please Go through your code Once more.
for (i = n - 1; i >= 0; i--)
{
anothersmallestvalue = x;
for (j = 0; j <= lengthof_B ; j++)
{
if (a[i] == anothersmallestvalue)
{
temp = b[j];
c[temp - 1] = anothersmallestvalue;
b[j] = b[j] -1 ;// Possible Mistake I think here
}
anothersmallestvalue++;
}
}
the very simple and stylish way is described and shown here.
en.wikipedia.org/wiki/Counting_sort#The_algorithm
Normal sorting your two loops should look like this
for (i = 0; i < lengthof_B - 1; i++)
{
for (j = i + 1; j < lengthof_B; j++)
{
}
}​

How to set a datagridview cell value color on basis of if condition

I have a datagridview with many columns and many rows of data and i want to set some cells color to red or green,so that i have used below code
And as my code illustrates the column "exam" is not reading and not entering into the if condition.please suggest me what to do for my issue.
dataGridView2_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)//I have used this event
string unit = Convert.ToString(dataGridView2.Columns["exam"]);//One of my datagridview
//column name is exam and in that column cells will be unit1 or unit2 or unit3 or unit 4 or quarterly or halfyearly or yearly
if (unit == "Unit1" || unit == "Unit2" || unit == "Unit3" || unit == "Unit4")
{
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
for (int j = 7; j < dataGridView2.Rows[i].Cells.Count; j++)
{
if (Convert.ToInt32(dataGridView2.Rows[i].Cells[j].Value) < 13)
{
dataGridView2.Rows[i].Cells[j].Style.ForeColor = Color.Red;
}
else
{
dataGridView2.Rows[i].Cells[j].Style.ForeColor = Color.Green;
}
}
}
}
else
{
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
for (int j = 7; j < dataGridView2.Rows[i].Cells.Count; j++)
{
if (Convert.ToInt32(dataGridView2.Rows[i].Cells[j].Value) < 35 )
dataGridView2.Rows[i].Cells[j].Style.ForeColor = Color.Red;
else
dataGridView2.Rows[i].Cells[j].Style.ForeColor = Color.Green;
}
}
}
Instead of using == notation use .Equals() to check whether they are equal or not.
if (unit.Equals("Unit 1") ||unit.Equals("Unit1") || unit.Equals("Unit2") || unit.Equals("Unit3") || unit.Equals("Unit4"))
{
//your logic
}
apply the above logic and also use
string data = (string)MyDataGridView[Colnum, Rownum].Value;
Then you can simply loop rows and columns
Cheers! Hope it helps.
This is the code what i wanted exactly..
I hope it will help others..
private void dataGridView3_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
for (int i = 0; i < dataGridView3.Rows.Count; i++)
{
string unit = Convert.ToString(dataGridView3.Rows[i].Cells[6].Value);
if (unit == "Unit1" || unit == "Unit2" || unit == "Unit3" || unit == "Unit4")
{
for (int k = 7; k < dataGridView3.Rows[i].Cells.Count; k++)
{
int val = Convert.ToInt32(dataGridView3.Rows[i].Cells[k].Value);
if (val <= 12)
{
dataGridView3.Rows[i].Cells[k].Style.ForeColor = Color.Red;
}
else
{
dataGridView3.Rows[i].Cells[k].Style.ForeColor = Color.Green;
}
}
}
else
{
for (int j = 7; j < dataGridView3.Rows[i].Cells.Count; j++)
{
if (Convert.ToInt32(dataGridView3.Rows[i].Cells[j].Value) < 35)
{
dataGridView3.Rows[i].Cells[j].Style.ForeColor = Color.Red;
}
else
dataGridView3.Rows[i].Cells[j].Style.ForeColor = Color.Green;
}
}
}
}

Categories