[英]Refactoring C# code for conversion to a WPF application (Visual Studio)
對於這個猜謎游戲,我想重構代碼的玻璃大炮以轉換為 WPF 應用程序。 我可以用來縮短此/成功轉換的任何方法以及 VS 上的提示,一般來說,將不勝感激。
我使用 WPF 應用程序(核心)作為該程序的模板。 以及使用 Microsoft 教程來構建它。 這個項目的UI基本就完成了,只需要導入這段代碼。
請注意,我在高中,所以我的知識范圍不是那么大。
編輯:好的。
到目前為止我所做的是; 關於 MainWindow.xaml 是兩種方法。 初始化 rnd 計算的公共方法。 還有一個“Button_Click”私有方法,一旦用戶提交他們的猜測,“游戲”就會看到它是否匹配並顯示他們是對還是錯,包括他們猜對了多長時間。
class MainClass
{
public static void Main (string[] args)
{
Random rnd = new Random();
int ans = rnd.Next(1,10);
Console.WriteLine("Pick an integer between 1 and 10");
var num1 = Console.ReadLine();
int v1 = Convert.ToInt32(num1);
if(v1 == ans)
{
int count = 1;
Console.WriteLine($"{v1} is correct. You Win!");
Console.WriteLine($"It took you to {count} gues find the number {ans}." );
}
else
{
if(v1<ans){
Console.WriteLine("To high");
}
else
Console.WriteLine("To low");
Console.WriteLine("Pick an interger between 1 and 10");
Console.WriteLine($"{v1} isn't correct. Try again!");
var num2 = Console.ReadLine();
int v2 = Convert.ToInt32(num2);
if(v2 == ans)
{
int count = 2;
Console.WriteLine($"{v2} is correct. You Win!");
Console.WriteLine($"It took you {count} gueses to find the number {ans}" );
}
else
{
if(v1<ans){
Console.WriteLine("To high");
}
else
Console.WriteLine("To low");
Console.WriteLine("Pick an interger between 1 and 10");
Console.WriteLine($"{v2} isn't correct. Try again!");
var num3 = Console.ReadLine();
int v3 = Convert.ToInt32(num3);
if(v3 == ans)
{
int count = 3;
Console.WriteLine($"{v3} is correct. You Win!");
Console.WriteLine($"It took you {count} gueses to find the number {ans}" );
}
else
{
if(v1<ans){
Console.WriteLine("To high");
}
else
Console.WriteLine("To low");
Console.WriteLine("Pick an interger between 1 and 10");
Console.WriteLine($"{v3} isn't correct");
}
Console.WriteLine($"You Lose! The correct number is {ans}. ");
}
}
}
}
這里發生了這么多事情,我們需要很多時間來解釋。
讓我嘗試了解基礎知識。 C# 中的類是狀態和行為的藍圖。
那個時候,你可以將你的代碼建模為GameRound
public class GameRound {
private int noOfTries;
private int maxNoOfTries;
private int correctNumber;
private bool success;
public bool HasRoundEnded { get {
return maxNoOfTries == noOfTries;
}
}
public bool Success { get {
return success;
}
}
public GameRound() {
Random rnd = new Random();
int ans = rnd.Next(1,10);
correctNumber = ans;
}
public bool GuessSolution(int guess) {
if (guess == correctNumber) {
this.success = true;
} else {
this.success = false;
maxNoOfTries++;
}
return this.success;
}
您可以看到您的大部分邏輯都包含在一個類中。 我會把它留給你來弄清楚如何使用它。
您會注意到沒有對 Console.Write 或 read 的依賴。 您可以在控制台應用程序或 UI 甚至網站中使用該代碼。 發生這種情況是因為我們將類的關注點分開以僅對游戲回合進行建模。
另一條建議是,對提供的類使用while
循環,以解決控制台應用程序中的問題。 這樣你就會理解如何使用類的重復結構和對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.