0
테이블 개체를 만들었습니다.NullReferenceException이 (가) 해제되었습니다
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 GameMachineWF
{
public partial class Form1 : Form
{
Label firstClicked = null;
Label secoundClicked = null;
int rows;
int cols;
Random random = new Random();
TableLayoutPanel table;
List<String> icons = new List<string>()
{
"!", "!" , "N", "N", "Y", "Y", "k", "k",
"," , ",", "b", "b", "w","w", "v", "v"
};
public Form1(int rows, int cols)
{
InitializeComponent();
LoadGame(rows, cols);
}
public void LoadGame(int rows, int cols)
{
TableLayoutPanel table = new TableLayoutPanel();
table.Dock = DockStyle.Fill;
table.ColumnCount = cols;
table.RowCount = rows;
table.BackColor = Color.CornflowerBlue;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
Label label = new Label();
label.Dock = DockStyle.Fill;
label.Name = "label" + i + "" + j;
label.Text = "c";
label.Click += this.label_Click;
label.Size = new Size(100, 100);
label.Font = new Font("Webdings", this.Font.Size);
label.BorderStyle = BorderStyle.Fixed3D;
table.Controls.Add(label, i, j);
table.AutoSize = true;
}
}
this.Controls.Add(table);
this.Size = new Size(rows * 100 + 50, cols * 100 + 50);
foreach (Control control in table.Controls)
{
Label iconLabel = control as Label;
if (iconLabel != null)
{
int randomNumber = random.Next(icons.Count);
iconLabel.Text = icons[randomNumber];
iconLabel.ForeColor = iconLabel.BackColor;
icons.RemoveAt(randomNumber);
}
}
}
private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
{
}
private void label_Click(object sender, EventArgs e)
{
if (timer1.Enabled == true)
return;
Label clicklabel = sender as Label;
if (clicklabel != null)
{
if (clicklabel.ForeColor == Color.Black)
{
return;
}
if (firstClicked == null)
{
firstClicked = clicklabel;
firstClicked.ForeColor = Color.Black;
return;
}
}
secoundClicked = clicklabel;
secoundClicked.ForeColor = Color.Black;
formWinner();
if (firstClicked.Text == secoundClicked.Text)
{
firstClicked = null;
secoundClicked = null;
return;
}
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
firstClicked.ForeColor = firstClicked.BackColor;
secoundClicked.ForeColor = secoundClicked.BackColor;
firstClicked = null;
secoundClicked = null;
}
private void formWinner()
{
foreach (Control controls in table.Controls)
{
Label lblWin = controls as Label;
if (lblWin != null)
{
if (lblWin.ForeColor == lblWin.BackColor)
{
return;
}
}
}
MessageBox.Show("You won. Congratulations");
Close();
}
}
양식이 이벤트에서 인수를 가져옵니다 :
private void x4ToolStripMenuItem_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1(4, 4);
f1.ShowDialog();
}
NullReferenceException이이 FormWinner() 메소드에서 tablecontrols 요소에 unhalted 된 코드를 참조하십시오.
위 코드는 내가 일하고있는 쌍 게임을위한 게임으로, C#의 Microsoft Pair Game Tutorial에서 영감을 받았습니다.
예 :-) u가 옳습니다. – MxM