2015-11-26 33 views
0

我正在創建一個雙人玩家骰子游戲,玩家可以與其他用戶或計算機一起玩。我很難弄清楚如何創建一個雙人遊戲。我不知道如果我要爲每個用戶創建單獨的類,然後創建該類的對象有兩個獨立的播放器或者,如果我只需要創建一個變量,像如何創建第二個玩家/計算機

static int player = 1; 

並將其分配給特定區域並使用模數來確定哪個球員已經上場。

此外,在我的roll_Btn方法下,您將看到我正試圖在骰子滾動「1」並清除指定字段時切換到下一個用戶,但是程序結束我曾嘗試再次擲骰子。請參閱下面的代碼。感謝您的幫助和指導。

public partial class Game : Form 
{ 
    public Game() 
    { 
     InitializeComponent(); 
    } 
    static int player = 1; 
    private void Game_Load(object sender, EventArgs e) 
    { 
     oneNameTxt.Text = diceFrm.player1.ToUpper(); 
     twoNameTxt.Text = diceFrm.player2.ToUpper(); 
    } 

    private void endBtn_Click(object sender, EventArgs e) 
    { 
     diceFrm end = new diceFrm(); 
     end.Show(); 
     this.Hide(); 
    } 
    private void standBtn_Click(object sender, EventArgs e) 
    { 
     oneScoreTxt.Text = totalTxt.Text; 
    } 

    private void rollBtn_Click(object sender, EventArgs e) 
    { 
     int t1 = Convert.ToInt32(turnsTxt.Text); 
     int t2 = t1 + 1; 
     turnsTxt.Text = t2.ToString(); 

     Random rand = new Random(); 
     int dice = rand.Next(1, 7); 
     rollTxt.Text = dice.ToString(); 
     int d1 = Convert.ToInt32(totalTxt.Text); 
     int d2 = d1 + dice; 
     totalTxt.Text = d2.ToString(); 
     if(dice == 1) 
     { 
      player++; 
      rollTxt.Text = String.Empty; 
      turnsTxt.Text = String.Empty; 
      totalTxt.Text = String.Empty; 
     } 
    } 
    private void oneScoreTxt_TextChanged(object sender, EventArgs e) 
    { 
     int score1 = Convert.ToInt32(oneScoreTxt.Text); 
     int score2 = Convert.ToInt32(twoScoreTxt.Text); 

     if (score1 >= 100 || score2 >= 100) 
     { 
      whatLbl.Text = "Winner"; 
     } 
     else 
     { 
      whatLbl.Text = "Turn"; 
     } 
    } 
+1

您設置了turnsTxt.Text = String.Empty;而不是將其分配給有效整數的字符串表示形式,並且當再次單擊該按鈕時,您嘗試將文本框值轉換爲一個整數,其中int t1 = Convert.ToInt32(turnsTxt.Text); –

+0

謝謝你,完美的作品。 @OguzOzgul –

回答

0

正如Ogul厄茲居爾說,

private void rollBtn_Click(object sender, EventArgs e) 
    { 
     ... 
     if (dice == 1) 
     { 
      ... 
      turnsTxt.Text = String.Empty; 
      ... 
     } 
    } 

當你擲出1,你turnsTxt.Text =的String.Empty,因此,當下次你滾,

private void rollBtn_Click(object sender, EventArgs e) 
    { 
     int t1 = Convert.ToInt32(turnsTxt.Text); // program crash 
     ... 
    } 

您程序將崩潰可怕。

解決方案:我會建議您使用TryParse代替轉換整個代碼。它將更加強大。

例如,

private void rollBtn_Click(object sender, EventArgs e) 
    { 
     int t1 = 0; 
     int.TryParse(turnsTxt.Text, out t1) 
     int t2 = t1 + 1; 
     turnsTxt.Text = t2.ToString(); 
     ... 
     //rest of your code 
    } 
+0

非常感謝。回覆晚了非常抱歉。完美的作品。 @interceptwind –