我刚刚完成了 Head First C# 中的一个练习,在那里我构建了一个打字游戏。该书将其留给读者以弄清楚如何制作,以便玩家一旦输了就可以开始新的游戏。用户输掉游戏后,窗口显示“游戏结束”消息。我想弹出一个新窗口,询问用户在屏幕上关闭游戏后是否愿意再次玩游戏。我想要两个按钮;一个说“不”,一个说“是”。我所坚持的是,如果用户决定要再次播放,我应该(或将)如何重新启动应用程序。我将在下面复制并粘贴我的代码:
namespace _7HeadFirstProject
{
public partial class Form1 : Form
{
Random random = new Random();
Stats stats = new Stats();
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
// Add a random key to the ListBox
listBox1.Items.Add((Keys)random.Next(65, 90));
if (listBox1.Items.Count > 7)
{
listBox1.Items.Clear();
listBox1.Items.Add("Game Over");
timer1.Stop();
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
// If the user pressed a key that's in the ListBox...
// ... remove it and then make the game a little faster
if (listBox1.Items.Contains(e.KeyCode))
{
listBox1.Items.Remove(e.KeyCode);
listBox1.Refresh();
if (timer1.Interval > 400)
timer1.Interval -= 10;
if (timer1.Interval > 250)
timer1.Interval -= 7;
if (timer1.Interval > 100)
timer1.Interval -= 2;
difficultyProgressBar.Value = 800 - timer1.Interval;
// The user pressed a correct key, so update the Stats object...
// ...by calling its Update() method with the argument true
stats.Update(true);
}
else
{
// The user pressed an incorrect key, so update the Stats object...
// ...by calling its Update() method with the argument false
stats.Update(false);
}
// Update the labels on the StatusStrip
correctLabel.Text = "Correct: " + stats.Correct;
missedLabel.Text = "Missed: " + stats.Missed;
totalLabel.Text = "Total: " + stats.Total;
accuracyLabel.Text = "Accuracy: " + stats.Accuracy + "%";
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
MessageBox.Show("Would you like to play again?");
if
}
}
}
不同的班级:
namespace _7HeadFirstProject
{
class Stats
{
public int Total = 0;
public int Missed = 0;
public int Correct = 0;
public int Accuracy = 0;
public void Update(bool correctKey)
{
Total++;
if (!correctKey)
{
Missed++;
}
else
{
Correct++;
}
Accuracy = 100 * Correct / Total;
}
}
}
你让整个游戏都在工作,所以不要管那个表格。将另一个表单添加到您的项目中,然后将新表单设置为启动表单。您可以通过打开Program.cs
和修改此行将其设置为启动表单:
// Instead of Form1 put the name of your new form
Application.Run(new Form1());
双击新表单并将此代码放入其中:
// Note: Your load method may have a different name.
private void Form2_Load(object sender, EventArgs e)
{
this.StartNewGame();
}
private void GameForm_FormClosed(object sender, FormClosedEventArgs e)
{
if (MessageBox.Show("Continue?", "Continue?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
this.StartNewGame();
}
}
private void StartNewGame()
{
// Your game form may have a different name so change this to that name
var gameForm = new Form2();
gameForm.FormClosed += GameForm_FormClosed;
gameForm.Show();
}
每次用户按下对话框上的 yes 按钮时,您都在创建一个全新的表单实例(游戏)。在这个新表单中,您还可以拥有一个数组来跟踪游戏总数和每场游戏的得分,以便在用户选择否的情况下显示它。您只需要这样的东西:
var games = new List<Stats>();
// keep adding to it every time you call StartNewGame() method.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句