C# 猜谜游戏 - Windows 窗体应用程序 - 如何配置“再次播放按钮”并保持总分

本文关键字:播放 按钮 配置 Windows 游戏 窗体 应用程序 何配置 | 更新日期: 2023-09-27 18:33:17

我是 c# 的新手,我需要一些关于我的小应用程序的帮助。

我想要一个按钮,可以在完成后重新开始游戏,但程序需要保持总分。(您猜谜会获得积分)

提前感谢,

菲利普

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GuessingGame
{
 public partial class TheUltimateGuessingGame : Form
 {
    public TheUltimateGuessingGame()
    {
        InitializeComponent();
    }
    int number;
    int numberoftries;
    int points;
    int total = 0;
    private void Form1_Load(object sender, EventArgs e)
    {
        Random generator = new Random();
        number = generator.Next(0, 101);
        MessageBox.Show("Try to guess a number between 1 and 100");
    }
    private void PlayAgainButton_Click(object sender, EventArgs e)
    {
        InitializeComponent();
    }
    private void button_guess_Click(object sender, EventArgs e)
    {
        int guess = Convert.ToInt32(textBox_guess.Text);
        if (guess > number)
        {
            textbox_showdifference.Text = ("Guess was too high, try again!");
        }
        if (guess < number)
        {
            textbox_showdifference.Text = ("Guess was too low, try again!");
        }
        if (guess == number)
        {
            textbox_showdifference.Text = ("Awesome, guess was right!");
            MessageBox.Show("It took you " + Convert.ToString(numberoftries) + " tries 
            to guess the right number");
            if (numberoftries <= 3)
            {
                points = 10;
            }
            if (numberoftries >= 4 && numberoftries <= 6)
            {
                points = 5;
            }
            if (numberoftries >= 7)
            {
                points = 2;
            }
            total = total + points;
            ScoreBoard1.Text = ("Here are your points --> " + points + "'nHere are your total points --> " + total);
        }
        ++numberoftries;

    }
     private void exitbutton_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }
}

}

C# 猜谜游戏 - Windows 窗体应用程序 - 如何配置“再次播放按钮”并保持总分

为什么不是这个?

private void PlayAgainButton_Click(object sender, EventArgs e)
{
    Random generator = new Random();
    number = generator.Next(0, 101);
    numberoftries = 0;
    MessageBox.Show("Try to guess a number between 1 and 100");
}

InitializeComponent是分析 XAML 以生成窗体的方法。它不用于重置对象的状态。