I tried to replicate Minesweeper as a small practise in coding with Windows Forms.
After some time, when I ran the program, the Form did neither display nor show up in the task bar.
Eventually, I was able to track down the problem to a function I wrote, that was called in the Form1 constructor. Whenever it was in its constructor, the Form did not show up whenever I pressed F5. There are no error messages shown, it's just the window not popping up.
Here is the code I wrote. The function causing problems is the Setup() function called in the Form1 constructor:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Minesweeper
{
public partial class Form1 : Form
{
private int bombs = 40;
private Size gridSize = new Size (20, 20);
private Random random = new Random();
private int[,] values;
public Form1()
{
InitializeComponent();
Setup();
}
//Setup / Game start
private void Setup()
{
//Set grid size
values = new int[gridSize.Width, gridSize.Height];
//Place bombs
if (bombs < gridSize.Width * gridSize.Height)
{
for (int i = 0; i < bombs; i )
{
Point p = new Point(random.Next(0, gridSize.Width), random.Next(0, gridSize.Height));
while (values[p.X, p.Y] != 9)
{
p = new Point(random.Next(0, gridSize.Width), random.Next(0, gridSize.Height));
}
values[p.X, p.Y] = 9;
}
}
//Calculate values
for (int x = 0; x < gridSize.Width; x )
{
for (int y = 0; y < gridSize.Height; y )
{
if (values[x, y] >= 9)
{
ChangeValueAt(x - 1, y - 1, 1);
ChangeValueAt(x - 1, y, 1);
ChangeValueAt(x - 1, y 1, 1);
ChangeValueAt(x, y - 1, 1);
ChangeValueAt(x, y 1, 1);
ChangeValueAt(x 1, y - 1, 1);
ChangeValueAt(x 1, y, 1);
ChangeValueAt(x 1, y 1, 1);
}
}
}
}
//Change value in grid
private void ChangeValueAt(int x, int y, int changeBy)
{
if (values.GetLength(0) > x && values.GetLength(1) > y && values[x, y] != 9)
{
values[x, y] = changeBy;
}
}
}
}
Does anyone know why that happens?
PS: I am very new to coding, I know my code is often not very tidy and there might be a few bad memory usages, but I would just like to know if anyone could help me out here.
CodePudding user response:
That's because the while-loop never ends. The fist time the for-loop runs, no value[,x,y]
has been set to 9
yet.
So, the while condition values[p.X, p.Y] != 9
will always be true.
I would write
for (int i = 0; i < bombs; i ) {
Point p;
do {
p = new Point(random.Next(0, gridSize.Width),
random.Next(0, gridSize.Height));
} while (values[p.X, p.Y] == 9);
values[p.X, p.Y] = 9;
}
Also, the lower bounds must be tested as well:
private void ChangeValueAt(int x, int y, int changeBy)
{
if (0 <= x && x < values.GetLength(0) &&
0 <= y && y < values.GetLength(1) &&
values[x, y] != 9) {
values[x, y] = changeBy;
}
}