《Head First C#》外星人入侵WPF編寫源碼


@

引言

自學的C#,看了幾本教材講的都是程序代碼,網上找的也有視屏,但都比較老了。只會打些代碼為不曉得為什么要這樣打感覺很別扭,在朋友的推薦下先選擇了這本《Head First C#》先大致的了解下C#。
這本書的第一章我就遇見了問題,要裝IDE選的是VS2012 for win8的,這完全和我的系統不配我是用的VS2017+win10,想着應該是一樣的,但是沒有找到windows store,我尋思着估計我只安裝了for .NET沒有安裝windows平台通用的那個環境,要是選擇在安裝那個環境的話12G空間,懶得裝。書上說明了使用WPF可以打大部分代碼,那就將就着用吧!書上給了參考PDF的下載網址可是用梯子也連不上,打了前綴發現進了他們公司的主站。估計網址換了把,CSDN上也沒找到那個PDF資源。自己瞎琢磨着來吧,這個博客是個記錄,希望對你有用。

前期工作

  1. 打開VS,創建WPF窗體;
    創建界面
  2. 照書上一步一步來搭建界面,基本一樣
    在這里插入圖片描述
  3. 搭建好了我們就來寫代碼,代碼里面有點不一樣我會說明的

代碼編寫

注意事項:

  1. 引用的地方:這里你會發現沒有using windows.UI.Xaml;之類的引用。這是你沒安裝他的環境因而沒有這些動態庫。
    解決方法:用using System.Windows.*,就行,你會發現其實去掉UI,Xaml其他字段都一樣。
  2. 關於事件里面沒有PointerPressed和PointerMoved等等這個它可以發布到平台上平板也要用估計是他們把事件給優化了,不過不用慌,看得懂英文的就可以類推不就是個鼠標按壓事件和鼠標移動事件嗎?照着我們有的事件來就行。
    解決方法:使用MouseDown和MouseMoved代替其他事件一樣。
  3. PlayArea_MouseMove函數里面有個Point的語句,是不是按照書上敲又報錯了!這個我也不曉得為啥給可能還是環境的問題吧!.NET的WPF確實沒有那幾個函數。不過仔細讀下就可以理解是獲取PlayArea里面的鼠標位置,進行鼠標位置判斷的。網上查了下WPF獲取鼠標位置的幾種方法這發現使用這種更合適跟簡單,還不用像書上那樣進行鼠標的轉換,用e.GetPosition(playArea);直接就使用的是相對與playArea的鼠標位置。
    解決辦法:使用e.GetPosition()

其他的倒沒有什么問題,有問題留言,如果我可以幫助你的話。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Media.Animation;
using System.Windows.Threading;

namespace SaveHuman
{
    /// <summary>
    /// MainWindow.xaml 的交互邏輯
    /// </summary>
    public partial class MainWindow : Window
    {
        Random random = new Random();
        DispatcherTimer enemyTimer = new DispatcherTimer();
        DispatcherTimer targetTimer = new DispatcherTimer();
        bool humanCaptured = false;
        public MainWindow()
        {
            InitializeComponent();

            enemyTimer.Tick += EnemyTimer_Tick;//2019.10.30 22點21分
            enemyTimer.Interval = TimeSpan.FromSeconds(2);//2秒增加一個敵人

            targetTimer.Tick += TargetTimer_Tick;
            targetTimer.Interval = TimeSpan.FromSeconds(.1);//0.1秒執行一次
        }
        /// <summary>
        /// 進度條計時器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TargetTimer_Tick(object sender, EventArgs e)
        {
            progressBar.Value += 1;
            if (progressBar.Value >= progressBar.Maximum)
            {
                EndTheGame();
            }
        }

        /// <summary>
        /// 游戲結束
        /// </summary>
        #region 游戲結束
        private void EndTheGame()
        {
            if (!playArea.Children.Contains(gameoverText))
            {
                enemyTimer.Stop();
                targetTimer.Stop();
                humanCaptured = false;
                starbutton.Visibility = Visibility.Visible;
                playArea.Children.Add(gameoverText);
            }
        }
        #endregion
        /// <summary>
        /// 添加敵人的計時器
        /// </summary>

        private void EnemyTimer_Tick(object sender, EventArgs e)
        {
            AddEnemy();
        }
        /// <summary>
        /// 點擊Star開始游戲
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Starbutton_Click(object sender, RoutedEventArgs e)
        {
            StarGame();

        }
        /// <summary>
        /// 開始游戲初始化
        /// </summary>
        private void StarGame()
        {
            human.IsHitTestVisible = true;
            humanCaptured = false;
            progressBar.Value = 0;
            starbutton.Visibility = Visibility.Collapsed;
            playArea.Children.Clear();
            playArea.Children.Add(target);
            playArea.Children.Add(human);
            enemyTimer.Start();
            targetTimer.Start();
        }
        /// <summary>
        /// 添加敵人
        /// </summary>
        private void AddEnemy()
        {
            ContentControl enemy = new ContentControl();
            enemy.Template = Resources["EnemyTemplate"] as ControlTemplate;
            AnimateEnemy(enemy, 0, playArea.ActualWidth - 100, "(Canvas.Left)");
            AnimateEnemy(enemy, random.Next((int)playArea.ActualHeight - 100), random.Next((int)playArea.ActualHeight - 100), "(Canvas.Top)");
            playArea.Children.Add(enemy);

            enemy.MouseEnter += Enemy_MouseEnter;
        }
        /// <summary>
        /// 鼠標進入敵人
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Enemy_MouseEnter(object sender, MouseEventArgs e)
        {
            if (humanCaptured)
            {
                EndTheGame();
            }
        }
        /// <summary>
        /// 動畫函數
        /// </summary>
        /// <param name="enemy"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="propertyToAnimate"></param>
        private void AnimateEnemy(ContentControl enemy, double from, double to, string propertyToAnimate)
        {
            Storyboard storyboard = new Storyboard() { AutoReverse = true, RepeatBehavior = RepeatBehavior.Forever };
            DoubleAnimation animation = new DoubleAnimation()
            {
                From = from,
                To = to,
                Duration = new Duration(TimeSpan.FromSeconds(random.Next(4, 6)))
            };
            Storyboard.SetTarget(animation, enemy);
            Storyboard.SetTargetProperty(animation, new PropertyPath(propertyToAnimate));
            storyboard.Children.Add(animation);
            storyboard.Begin();
        }

        
        /// <summary>
        /// 人類是否到達目的地的判斷
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Target_MouseEnter(object sender, MouseEventArgs e)
        {
            if(targetTimer.IsEnabled && humanCaptured)
            {
                progressBar.Value = 0;
                Canvas.SetLeft(target, random.Next(100, (int)playArea.ActualWidth - 100));
                Canvas.SetTop(target, random.Next(100, (int)playArea.ActualHeight - 100));
                Canvas.SetLeft(human, random.Next(100, (int)playArea.ActualWidth - 100));
                Canvas.SetTop(human, random.Next(100, (int)playArea.ActualHeight - 100));
                humanCaptured = false;
                human.IsHitTestVisible = true;

            }
        }
        /// <summary>
        /// 鼠標在游戲區域移動
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PlayArea_MouseMove(object sender, MouseEventArgs e)
        {
            if (humanCaptured)
            {
                //獲取鼠標相對於palyArea的位置,無需書上的轉換這是wpf與windows Store的不同
                //對於這個不理解可以把playArea改為null試試看看區別就曉得了
                Point pointerProsition = e.GetPosition(playArea);

                
                if((Math.Abs(pointerProsition.X-Canvas.GetLeft(human))>human.ActualWidth*3) || (Math.Abs(pointerProsition.Y - Canvas.GetTop(human)) > human.ActualHeight * 3))
                {
                    humanCaptured = false;
                    human.IsHitTestVisible = true;

                }
                else
                {
                    Canvas.SetLeft(human, pointerProsition.X - human.ActualWidth / 2);
                    Canvas.SetTop(human, pointerProsition.Y - human.ActualHeight / 2);

                }
            }
        }
        /// <summary>
        /// 鼠標拖着人類離開游戲區域
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PlayArea_MouseLeave(object sender, MouseEventArgs e)
        {
            if (humanCaptured)
            {
                EndTheGame();
            }
        }

        /// <summary>
        /// 鼠標左鍵點擊人類的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Human_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (enemyTimer.IsEnabled)
            {
                humanCaptured = true;
                human.IsHitTestVisible = false;
                //Console.WriteLine("鼠標按下選中狀態:" + humanCaptured);

            }
        }

        
    }
}

只要努力沒有什么困難可以難倒你,加油騷年!

————————————————————————————————Boting_ISME
![在這里插入圖片描述](https://img-blog.csdnimg.cn/20191104205328137.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Mzc1MjA3MA==,size_16,color_FFFFFF,t_70#pic_center =300x)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM