[英]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.