【发布时间】:2015-06-29 05:42:28
【问题描述】:
我正在用 c# 创建一个简单的井字游戏,到目前为止我只有两种形式。
-
frmMain.(游戏主形态) -
frmPlayerInfo.(用于选择单人或2人)
我还创建了一个 Player 类。
所以我的想法是这样的。一旦玩家输入他们的名字,它将转到 Player 类中的属性并将值存储在私有变量中,以便我可以在主窗体上获取它以用于显示目的。 但是当我回到主窗体时,属性会返回 null,这是为什么呢?
这是我的代码。
Player Class...(我已经删除了与此问题无关的无关属性和变量)
class Player
{
#region PrivatVariables
private string _PlayerName1;
private string _PlayerName2;
#endregion
#region Properties
public string playerName1
{
get
{
return _PlayerName1;
}
set
{
_PlayerName1 = value;
}
}
public string playerName2
{
get
{
return _PlayerName2;
}
set
{
_PlayerName2 = value;
}
}
#endregion
public Player()
{
// Do nothing
}
internal void resetValues()
{
}
}
主窗体...(我只是包含主代码,我在窗体加载时调用新的游戏代码)
public partial class frmMain : Form
{
Player player = new Player();
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
// TODO : Set timer so that form can load first.
newGame();
}
private void newGame()
{
// Creating an instance of the Form used to take in player info.
frm_PlayerInfo playerInfo = new frm_PlayerInfo();
// This is going to pop up the player info form.
DialogResult dialogResult = playerInfo.ShowDialog();
LoadForm();
}
private void LoadForm()
{
grpBoxPlayer1.Text = player.playerName1;
}
玩家信息表... ()
public partial class frm_PlayerInfo : Form
{
Player player = new Player();
bool isAnimated;
public frm_PlayerInfo()
{
InitializeComponent();
}
private void frm_PlayerInfo_Load(object sender, EventArgs e)
{
// Setting player tow input visibility to false because there will always be one player.
this.txtPlayerName2.Visible = false;
this.lblPlayerName2.Visible = false;
}
private void btnNext_Click(object sender, EventArgs e)
{
btnNext.Visible = false;
// Used to slide the Form up or down.
slideAnimation(ref isAnimated);
}
private void btnStart_Click(object sender, EventArgs e)
{
// Populating the Player Properties
player.playerName1 = this.txtPlayerName1.Text;
if (this.txtPlayerName2.Text != "")
{
player.playerName2 = this.txtPlayerName2.Text;
}
// Calling the animation method to close the animation back up and then the form will be closed.
slideAnimation(ref isAnimated);
FadeOutAnimation();
}
【问题讨论】:
-
添加代码,用于填充播放器。
-
我认为您的“主表单”
player与“玩家信息表单”player不同。他们是独立的。但这只是一个假设。您需要显示声明和初始化“播放器信息表单”的播放器的代码。 -
大家好,请在编辑后立即查看,我在按钮开始单击时填充播放器属性,请查看最后一段代码。