我試圖復制 Minesweeper 作為使用 Windows 表單進行編碼的一個小練習。
一段時間后,當我運行程式時,表單既沒有顯示也沒有出現在任務欄中。
最終,我能夠將問題追溯到我撰寫的函式,該函式在 Form1 建構式中呼叫。每當它在其建構式中時,只要我按 F5,Form 就不會出現。沒有顯示錯誤訊息,只是沒有彈出視窗。
這是我寫的代碼。導致問題的函式是 Form1 建構式中呼叫的 Setup() 函式:
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;
}
}
}
}
有誰知道為什么會這樣?
PS:我對編碼很陌生,我知道我的代碼通常不是很整潔,可能會有一些不好的記憶體使用,但我想知道是否有人可以在這里幫助我。
uj5u.com熱心網友回復:
那是因為while回圈永遠不會結束。for回圈第一次運行時,value[,x,y]尚未設定為no 9。因此,while 條件values[p.X, p.Y] != 9將始終為真。
我會寫
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;
}
此外,還必須測驗下限:
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;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/426369.html
上一篇:我的代碼應該呈現立方體的正面,而是顯示背面。為什么?
下一篇:顯示串列只顯示節點的頭部
