我得到了一个制作一个tic tac toe游戏(大小为8 * 8)的任务,到目前为止我设法对主游戏进行编码但是我遇到了将玩家名称从新游戏形式传递到主游戏中的问题,任何人都可以帮助
mainform代码
public void NameValue1(TextBox NV1)
{
lblName1.Text = NV1.Text;
}
public void NameValue2(TextBox NV2)
{
lblName2.Text = NV2.Text;
}
private void mnuNewGame_Click(object sender, EventArgs e)
{
iFlag = 1; // This is used to run the paint function on the form
StartGame();
for (int i = 0; i < 64; i++)
{
this._btn[i].Click += new System.EventHandler(this.ClickControl);
this._btn[i].MouseMove += new MouseEventHandler(this.MoveControl); // DEBUG // these 2 allow me to check 'does my mouse hover on the right box?'
this._btn[i].MouseLeave += new System.EventHandler(this.LeaveControl); // DEBUG //
}
}
public void StartGame()
{
frmNewGame OpenForm = null;
OpenForm = new frmNewGame();
OpenForm.ShowDialog();
//lblName1.Text = "Player 1"; // PLACEHOLDER // these 2 are what I'm trying to replace to accept values from newgameform
//lblName2.Text = "Player 2"; // PLACEHOLDER //
lblName1.Visible = true;
lblName2.Visible = true;
Random RandomNumber = new Random();
int Start = RandomNumber.Next(0, 3);
if (Start == 1)
{
PlayerTurn = "Player1";
lblName1.Font = new Font("Microsoft Sans Serif", 17, FontStyle.Underline | FontStyle.Bold);
lblName2.Font = new Font("Microsoft Sans Serif", 17, FontStyle.Regular | FontStyle.Bold);
}
else if (Start == 2)
{
PlayerTurn = "Player2";
lblName1.Font = new Font("Microsoft Sans Serif", 17, FontStyle.Regular | FontStyle.Bold);
lblName2.Font = new Font("Microsoft Sans Serif", 17, FontStyle.Underline | FontStyle.Bold);
}
NumberTurn = 0;
for (int i = 0; i < 64; i++)
{
_btn[i].Text = "";
_btn[i].BackColor = Color.Yellow;
_btn[i].Visible = true;
_btn[i].Enabled = true;
}
}
newgameform的代码
public delegate void PassName1(TextBox tbxPlayerName1);
public delegate void PassName2(TextBox tbxPlayerName2);
private void btnOK_Click(object sender, EventArgs e)
{
frmConnectFour frmGame = new frmConnectFour();
PassName1 PN1 = new PassName1(frmGame.NameValue1);
PassName2 PN2 = new PassName2(frmGame.NameValue2);
this.DialogResult = DialogResult.OK;
}
正如您所看到的,我已经准备好表单之间的连接以读取播放器名称文本框(没有错误),但是我遇到了如何将其传递给mainform上的startgame()函数的问题
P.S:我可以根据需要上传解决方案
答案 0 :(得分:1)
这个问题已经讨论了好几千次,但每次都有点不同
在这种情况下,您可以在newgameform
中创建两个公共属性
当用户单击“确定”按钮时,您可以使用newgameform
上的TextBoxes值设置属性
然后很容易从主表单中读取它们。
public string Player1 {get; private set;}
public string Player2 {get; private set;}
private void btnOK_Click(object sender, EventArgs e)
{
this.Player1 = txtBoxForPlayer1.Text;
this.Player2 = txtBoxForPlayer2.Text;
this.DialogResult = DialogResult.OK;
}
并以主要形式
public void StartGame()
{
using(frmNewGame OpenForm = new frmNewGame())
{
if(DialogResult.OK == OpenForm.ShowDialog())
{
lblName1.Text = OpenForm.Player1;
lblName2.Text = OpenForm.Player2;
lblName1.Visible = true;
lblName2.Visible = true;
.....
}
}
}