2014-10-17 68 views
-1

所以我正在做一個基本的yahtzee程序我c#,並試圖做一個實際的GUI,而不只是使用控制檯。不過,我對文本框有問題。當我滾動骰子時,我希望文本框顯示滾動的數字。現在它什麼都沒顯示。我使用兩個類,一個用於實際程序,另一個用於處理gui。這是Yahtzee的類:Textbox不會更新

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace Yahtzee 
{ 
    class YahtzeeScorer { 
     Random rndm = new Random(); 
     Form1 gui = new Form1(); 
     String dice1, dice2, dice3, dice4, dice5; 

     public void rollDice() 
     { 
      String a = Console.ReadLine(); 
      this.dice1 = rndm.Next(1, 7).ToString(); 
      this.gui.tbDice_SetText(this.dice1); 
     } 

     static void Main(String[] args) { 
      Application.EnableVisualStyles(); 
      Application.SetCompatibleTextRenderingDefault(false); 
      YahtzeeScorer ys = new YahtzeeScorer(); 
      Application.Run(ys.gui); 
      ys.rollDice(); 
      Console.WriteLine("The result was: " + ys.dice1); 
      Console.Read(); 
     } 

    } 
} 

這是GUI Form1類:

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 Yahtzee 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     public void tbDice_SetText(String s) 
     { 
      //this.ActiveControl = tbDice; 
      Console.WriteLine("SetText"); 
      tbDice.Text = s; 
     } 

     public void textBox1_TextChanged(object sender, EventArgs e) 
     { 

     } 



    } 
} 

tbDice是文本框組件的名稱。有任何想法嗎?

回答

1

檢查線路:

Application.Run(ys.gui); 
ys.rollDice(); 

rollDice()不會被調用,直到退出應用程序,因爲直到它運行Main()線程將阻塞Application.Run()

取而代之,請嘗試撥打ys.rollDice(),如按鈕事件處理程序。

UPDATE

你通過把兩方面YahtzeeScorer混合您的遊戲邏輯和表示邏輯。我建議你移動遊戲邏輯到這樣一個單獨的類:

public class YahtzeeGame 
{ 
    public string rollDice() 
    { 
     return rndm.Next(1, 7).ToString(); 
    }  
} 


public partial class Form1 : Form 
{ 
    YahtzeeGame game = new YahtzeeGame(); 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    // You need to create a new Button on your form called btnRoll and 
    // add this as its click handler: 
    public void btnRoll_Clicked(object sender, EventArgs e) 
    { 
     tbDice.Text = game.rollDice(); 
    } 
} 
+0

所以我想我不能讓YahtzeeScorer的實例在Form1,我可以打電話從yahtzeescorer的buttonpress行動?我可以在YS中決定form1中的按鈕應該做什麼?我會感激一個例子 – Lymanax 2014-10-17 23:16:54

+0

非常感謝你的配偶,解決了我的問題! – Lymanax 2014-10-18 11:01:39