尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

除了问号基本实现了经典扫雷游戏(WPF)一(需求、思路和按钮代码)

除了问号基本实现了经典扫雷游戏(WPF)一(需求、思路和按钮代码) 摘要本文分享一个用 WPF 从零实现经典扫雷游戏的思路与代码。作者针对网上现成代码缺少右键排雷、首次点击不踩雷等核心体验的问题自定义了一个继承自 Button 的 GameBtn 按钮类通过 Opened 和 Signed 两个依赖属性封装打开与标记逻辑简化游戏主类设计并兼顾右键反悔等细节需求。突然想练手WPF扫雷游戏先上网查了下有不少下了几个没能找到能实现经典扫雷功能的代码尤其是右键排雷功能这可是这款游戏的灵魂还有就是第一次点击应保证不是雷问号不常用手速快的不太用省略也无妨。一、基本需求扫雷基本动作就是排雷和标记比较频繁的动作是对按钮的左击、右击判断胜利或失败记录用时它是一个坐标游戏。二、基本思路首先使用原生Button有较高复杂度打开判断、标记和周围雷数都需要数组记录好多都是这样做的所以我做了个新类继承自Button添加两个属性Opened和Signed把背景色变更和标记动作放在里面简化了游戏类的设计。其次本游戏玩复杂度较低但逻辑复杂度较高需要考虑多种情况比如右键排雷如果玩家右键按下后发现不对有一个反悔的需求怎么设计布雷看着有难度其实就几行代码只是理解有难度而已。三、基本代码一是按钮类public class GameBtn : Button { public static readonly DependencyProperty OpenedProperty; public static readonly DependencyProperty SignedProperty; public bool Opened { get { return (bool)GetValue(OpenedProperty); } set { SetValue(OpenedProperty, BooleanBoxes.Box(value)); } } public bool Signed { get { return (bool)GetValue(SignedProperty); } set { SetValue(SignedProperty, BooleanBoxes.Box(value)); } } internal static class BooleanBoxes { internal static object TrueBox true; internal static object FalseBox false; internal static object Box(bool value) { if (value) return TrueBox; else return FalseBox; } } static GameBtn() { OpenedProperty DependencyProperty.Register(Opened, typeof(bool), typeof(GameBtn), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, OnOpenedChanged)); SignedProperty DependencyProperty.Register(Signed, typeof(bool), typeof(GameBtn), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, OnSignedChanged)); } private static void OnSignedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is GameBtn button) { if (button.Opened) { return;//已点开不操作 } else if (button.Signed) { button.Content ; button.Foreground Brushes.Red; } else { button.Content null; button.Foreground Brushes.LightGray; } } } private static void OnOpenedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is GameBtn button) { if (button.Opened) { button.Background Brushes.LightYellow; } else { button.Background Brushes.LightGray; } } } protected override AutomationPeer OnCreateAutomationPeer() { return new ButtonAutomationPeer(this); } protected override void OnClick() { if (AutomationPeer.ListenerExists(AutomationEvents.InvokePatternOnInvoked)) { UIElementAutomationPeer.CreatePeerForElement(this)?.RaiseAutomationEvent(AutomationEvents.InvokePatternOnInvoked); } if (!Opened)//已点开左击无效 { base.OnClick(); } } }
返回列表