本文介绍了一款使用C#和WPF框架开发的简单打字射击游戏。该游戏允许玩家通过键盘输入来消除屏幕上的随机字母,同时提供了基础的游戏界面和控制按钮。
游戏界面设计采用了XAML语言,主要元素包括游戏区域、开始和暂停按钮等:
在代码实现方面,游戏利用了C#中的事件处理机制来响应用户的键盘输入,并通过定时器控制字母的生成和下落:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Threading; namespace TypingGame { public partial class MainWindow : Window { private Random _random = new Random(); private DispatcherTimer _letterTimer = new DispatcherTimer(); private DispatcherTimer _fallTimer = new DispatcherTimer(); private List _letters = new List(); public MainWindow() { InitializeComponent(); InitializeGame(); } private void InitializeGame() { this.WindowStartupLocation = WindowStartupLocation.CenterScreen; gameArea.Background = Brushes.White; _letterTimer.Interval = TimeSpan.FromMilliseconds(800); _letterTimer.Tick += LetterTimer_Tick; _fallTimer.Interval = TimeSpan.FromMilliseconds(50); _fallTimer.Tick += FallTimer_Tick; this.KeyDown += MainWindow_KeyDown; } private void MainWindow_KeyDown(object sender, KeyEventArgs e) { foreach (var label in gameArea.Children.OfType()) { if (label.Tag != null && label.Tag.ToString() == "letter" && e.Key.ToString().ToLower() == label.Content.ToString().ToLower()) { label.Tag = "hit"; // 处理击中逻辑 break; } } } private void LetterTimer_Tick(object sender, EventArgs e) { var letter = new Label { COntent= GetRandomLetter(), Width = 40, Height = 40, FOntSize= 25, Foreground = new SolidColorBrush(Color.FromRgb((byte)_random.Next(0, 255), (byte)_random.Next(0, 255), (byte)_random.Next(0, 255))), Tag = "letter" }; Canvas.SetLeft(letter, _random.Next(0, 670)); Canvas.SetTop(letter, 0); _letters.Add(letter); gameArea.Children.Add(letter); } private void FallTimer_Tick(object sender, EventArgs e) { foreach (var label in _letters.ToList()) { double top = Canvas.GetTop(label); Canvas.SetTop(label, top + 5); if (top >= gameArea.Height - 30) { gameArea.Children.Remove(label); _letters.Remove(label); } else if (label.Tag != null && label.Tag.ToString() == "hit") { gameArea.Children.Remove(label); _letters.Remove(label); } } } private char GetRandomLetter() { return (char)_random.Next('a', 'z' + 1); } private void StartButton_Click(object sender, RoutedEventArgs e) { _letterTimer.Start(); _fallTimer.Start(); } private void PauseButton_Click(object sender, RoutedEventArgs e) { _letterTimer.Stop(); _fallTimer.Stop(); } } }
以上代码实现了游戏的基本功能,包括字母的随机生成、根据用户输入消除字母以及字母的自动下落。未来可以考虑增加更多的功能,如计分系统、倒计时等,以增强游戏的趣味性和挑战性。