C#利用控件拖拽技术制作拼图游戏

 更新时间:2020年6月25日 11:29  点击:2510

主要实现的功能:

1.程序附带多张拼图随机拼图。
2.可手动添加拼图。
3.游戏成功判断。
4.30秒超时判断。

 Puzzle.cs

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;
using System.IO;
 
namespace Puzzle
{
  public partial class Puzzle : Form
  {
    //图片列表
    PictureBox[] pictureList = null;
    //图片位置字典
    SortedDictionary<string, Bitmap> pictureLocationDict = new SortedDictionary<string, Bitmap>();
    //Location List 
    Point[] pointList = null;
    //图片控件字典
    SortedDictionary<string, PictureBox> pictureBoxLocationDict = new SortedDictionary<string, PictureBox>();
    //拼图时间
    int second = 0;
    //所拖拽的图片
    PictureBox currentPictureBox = null;
    //被迫需要移动的图片
    PictureBox haveToPictureBox = null;
    //原位置
    Point oldLocation = Point.Empty;
    //新位置
    Point newLocation = Point.Empty;
    //鼠标按下坐标(control控件的相对坐标) 
    Point mouseDownPoint = Point.Empty;
    //显示拖动效果的矩形 
    Rectangle rect = Rectangle.Empty;
    //是否正在拖拽 
    bool isDrag = false;
 
    public Puzzle()
    {
      InitializeComponent();
      InitGame();
    }
 
    /// <summary>
    /// 初始化游戏资源
    /// </summary>
    public void InitGame()
    {
      pictureList = new PictureBox[9] { pictureBox1, pictureBox2, pictureBox3, pictureBox4, pictureBox5, pictureBox6, pictureBox7, pictureBox8, pictureBox9 };
      pointList = new Point[9] { new Point(0, 0), new Point(100, 0), new Point(200, 0), new Point(0, 100), new Point(100, 100), new Point(200, 100), new Point(0, 200), new Point(100, 200), new Point(200, 200) };
      if (!Directory.Exists(Application.StartupPath.ToString() + "\\Picture"))
      {
        Directory.CreateDirectory(Application.StartupPath.ToString() + "\\Picture");
        Properties.Resources.默认.Save(Application.StartupPath.ToString() + "\\Picture\\1.jpg");
        Properties.Resources._1.Save(Application.StartupPath.ToString() + "\\Picture\\2.jpg");
        Properties.Resources._2.Save(Application.StartupPath.ToString() + "\\Picture\\3.jpg");
        Properties.Resources._3.Save(Application.StartupPath.ToString() + "\\Picture\\4.jpg");
        Properties.Resources._4.Save(Application.StartupPath.ToString() + "\\Picture\\5.jpg");
        Properties.Resources.成功.Save(Application.StartupPath.ToString() + "\\Picture\\6.jpg");
        Properties.Resources.欢呼.Save(Application.StartupPath.ToString() + "\\Picture\\7.jpg");
      }
      Random r = new Random();
      int i = r.Next(7);
      Flow(Application.StartupPath.ToString() + "\\Picture\\"+i.ToString()+".jpg");
    }
 
    private void Puzzle_Paint(object sender, PaintEventArgs e)
    {
      if (rect != Rectangle.Empty)
      {
        if (isDrag)
        {
          e.Graphics.DrawRectangle(Pens.White, rect);
        }
        else
        {
          e.Graphics.DrawRectangle(new Pen(this.BackColor), rect);
        }
      }
    }
 
   
    /// <summary>
    /// 不好用
    /// </summary>
    /// <returns></returns>
    public PictureBox GetPictureBoxByLocation()
    {
      PictureBox pic = null;
      if (this.ActiveControl.Name.Contains("pictureBox"))
      {
        pic = (PictureBox)this.ActiveControl;
      }
      return pic;
 
    }
 
    public PictureBox GetPictureBoxByLocation(MouseEventArgs e)
    {
      PictureBox pic = null;
      foreach (PictureBox item in pictureList)
      {
        if (e.Location.X > item.Location.X && e.Location.Y > item.Location.Y && item.Location.X + 100 > e.Location.X && item.Location.Y + 100 > e.Location.X)
        {
          pic = item;
        }
      }
      return pic;
    }
 
    public PictureBox GetPictureBoxByLocation(int x,int y)
    {
      PictureBox pic = null;
      foreach (PictureBox item in pictureList)
      {
        if (x> item.Location.X && y > item.Location.Y && item.Location.X + 100 > x && item.Location.Y + 100 > y)
        {
          pic = item;
        }
      }
      return pic;
    }
 
    /// <summary>
    /// 通过hashcode获取picture,用mouseeventargs之后获取相对于picture的坐标不是相对窗体
    /// </summary>
    /// <param name="hascode"></param>
    /// <returns></returns>
    public PictureBox GetPictureBoxByHashCode(string hascode)
    {
      PictureBox pic = null;
      foreach (PictureBox item in pictureList)
      {
        if (hascode == item.GetHashCode().ToString())
        {
          pic = item;
        }
      }
      return pic;
    }
 
    private void pictureBox_MouseDown(object sender, MouseEventArgs e)
    {
      oldLocation = new Point(e.X, e.Y);
      currentPictureBox = GetPictureBoxByHashCode(sender.GetHashCode().ToString());
      MoseDown(currentPictureBox, sender, e);
    }
 
    public void MoseDown(PictureBox pic, object sender, MouseEventArgs e)
    {
      if (e.Button == MouseButtons.Left)
      {
        oldLocation = e.Location;
        rect = pic.Bounds;
      }
    }
 
    private void pictureBox_MouseMove(object sender, MouseEventArgs e)
    {
      if (e.Button == MouseButtons.Left)
      {
        isDrag = true;
        rect.Location = getPointToForm(new Point(e.Location.X - oldLocation.X, e.Location.Y - oldLocation.Y));
        this.Refresh();
 
      }
    }
 
    
 
    private void reset()
    {
      mouseDownPoint = Point.Empty;
      rect = Rectangle.Empty;
      isDrag = false;
    }
 
    private Point getPointToForm(Point p)
    {
      return this.PointToClient(pictureBox1.PointToScreen(p));
    }
 
    private void pictureBox_MouseUp(object sender, MouseEventArgs e)
    {
      oldLocation = new Point(currentPictureBox.Location.X, currentPictureBox.Location.Y);
      if (oldLocation.X + e.X > 300 || oldLocation.Y + e.Y > 300||oldLocation.X + e.X < 0 || oldLocation.Y + e.Y < 0)
      {
        return;
      }
      haveToPictureBox = GetPictureBoxByLocation(oldLocation.X + e.X, oldLocation.Y + e.Y);
      newLocation = new Point(haveToPictureBox.Location.X, haveToPictureBox.Location.Y);
      haveToPictureBox.Location = oldLocation;
      PictureMouseUp(currentPictureBox, sender, e);
      if ( Judge())
      {
        lab_result.Text = "成功!";
        //MessageBox.Show("恭喜拼图成功");
      }
    }
 
    public void PictureMouseUp(PictureBox pic, object sender, MouseEventArgs e)
    {
      if (e.Button == MouseButtons.Left)
      {
        if (isDrag)
        {
          isDrag = false;
          pic.Location = newLocation;
          this.Refresh();
        }
        reset();
      }
    }
 
    public void ExchangePictureBox(MouseEventArgs e)
    { }
 
    private void btn_sta_Click(object sender, EventArgs e)
    {
      MessageBox.Show(this.ActiveControl.Name);
    }
 
    /// <summary>
    /// 初始化
    /// </summary>
    /// <param name="path"></param>
    public void Flow(string path)
    {
      Image bm = CutPicture.Resize(path, 300, 300);
      CutPicture.BitMapList = new List<Bitmap>();
      for (int y = 0; y < 300; y += 100)
      {
        for (int x = 0; x < 300; x += 100)
        {
          //string key = x + "-" + y;
          Bitmap temp = CutPicture.Cut(bm, x, y, 100, 100);
          //pictureLocationDict.Add(key, temp);
          CutPicture.BitMapList.Add(temp);
        }
      }
      ImportBitMap();
    }
 
    /// <summary>
    /// 打乱数据
    /// </summary>
    /// <param name="pictureArray"></param>
    /// <returns></returns>
    public PictureBox[] DisOrderArray(PictureBox[] pictureArray)
    {
      PictureBox[] tempArray = pictureArray;
      for (int i = tempArray.Length - 1; i > 0; i--)
      {
        Random rand = new Random();
        int p = rand.Next(i);
        PictureBox temp = tempArray[p];
        tempArray[p] = tempArray[i];
        tempArray[i] = temp;
      }
      return tempArray;
    }
 
    /// <summary>
    /// 判断是否拼图成功
    /// </summary>
    /// <returns></returns>
    public bool Judge()
    {
      bool result = true;
      int i = 0;
      foreach (PictureBox item in pictureList)
      {
        if (item.Location != pointList[i])
        {
          result = false;
        }
        i++;
      }
      return result;
    }
 
    private void btn_import_Click(object sender, EventArgs e)
    {
      lab_result.Text = "";
      ofd_picture.ShowDialog();
      CutPicture.PicturePath = ofd_picture.FileName;
      Flow(CutPicture.PicturePath);
      CountTime();
    }
 
    /// <summary>
    /// 计时
    /// </summary>
    public void CountTime()
    {
      lab_time.Text = "0";
      timer1.Start();
    }
 
    /// <summary>
    /// 给piturebox赋值
    /// </summary>
    public void ImportBitMap()
    {
      try
      {
 
        int i = 0;// DisOrderArray(pictureList)
        foreach (PictureBox item in pictureList)
        {
          Bitmap temp = CutPicture.BitMapList[i];
          item.Image = temp;
          i++;
        }
        ResetPictureLocation();
      }
      catch (Exception exp)
      {
        Console.WriteLine(exp.Message);
      }
       
    }
 
    /// <summary>
    /// 打乱位置列表
    /// </summary>
    /// <returns></returns>
    public Point[] DisOrderLocation()
    {
      Point[] tempArray = (Point[])pointList.Clone();
      for (int i = tempArray.Length - 1; i > 0; i--)
      {
        Random rand = new Random();
        int p = rand.Next(i);
        Point temp = tempArray[p];
        tempArray[p] = tempArray[i];
        tempArray[i] = temp;
      }
      return tempArray;
    }
 
    /// <summary>
    /// 重新设置图片位置
    /// </summary>
    public void ResetPictureLocation()
    {
      Point[] temp = DisOrderLocation();
      int i = 0;
      foreach (PictureBox item in pictureList)
      {
        item.Location = temp[i];
        i++;
      }
    }
 
    /// <summary>
    /// 计时,超过30秒停止计时
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void timer1_Tick(object sender, EventArgs e)
    {
      second++;
      lab_time.Text = second.ToString();
      if (second == 30)
      {
        timer1.Stop();
        lab_result.Text = "失败!";
      }
    }
 
    private void btn_sta_Click_1(object sender, EventArgs e)
    {
      lab_result.Text = "";
      timer1.Start();
    }
 
 
 
  }
}

CutPicture.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
 
namespace Puzzle
{
  class CutPicture
  {
    public static string PicturePath = "";
    public static List<Bitmap> BitMapList = null;
    /// <summary>
    /// 剪切图片
    /// </summary>
    /// <param name="b">图片</param>
    /// <param name="StartX">X坐标</param>
    /// <param name="StartY">Y坐标</param>
    /// <param name="iWidth">宽</param>
    /// <param name="iHeight">高</param>
    /// <returns></returns>
    public static Bitmap Cut(Image b, int StartX, int StartY, int iWidth, int iHeight)
    {
      if (b == null)
      {
        return null;
      }
      int w = b.Width;
      int h = b.Height;
      if (StartX >= w || StartY >= h)
      {
        return null;
      }
      if (StartX + iWidth > w)
      {
        iWidth = w - StartX;
      }
      if (StartY + iHeight > h)
      {
        iHeight = h - StartY;
      }
      try
      {
        Bitmap bmpOut = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);
        Graphics g = Graphics.FromImage(bmpOut);
        g.DrawImage(b, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(StartX, StartY, iWidth, iHeight), GraphicsUnit.Pixel);
        g.Dispose();
        return bmpOut;
      }
      catch
      {
        return null;
      }
    }
 
    /// <summary>
    /// 保存图片到根目录的Pictures文件夹下
    /// </summary>
    /// <param name="path">文件路径</param>
    /// <param name="iWidth">调整的宽</param>
    /// <param name="iHeignt">调整的高</param>
    /// <returns></returns>
    public static Image Resize(string path, int iWidth, int iHeignt)
    {
      Image thumbnail = null;
      try
      {
        var img = Image.FromFile(path);
        thumbnail = img.GetThumbnailImage(iWidth, iHeignt, null, IntPtr.Zero);
        thumbnail.Save(Application.StartupPath.ToString() + "\\Picture\\img.jpeg");
      }
      catch (Exception exp)
      {
        Console.WriteLine(exp.Message);
      }
      return thumbnail;
    }
 
    
  }
}

mouse_down

private void pictureBox_MouseDown(object sender, MouseEventArgs e)
    {
      oldLocation = new Point(e.X, e.Y);
      currentPictureBox = GetPictureBoxByHashCode(sender.GetHashCode().ToString());
      MoseDown(currentPictureBox, sender, e);
    }
 
    public void MoseDown(PictureBox pic, object sender, MouseEventArgs e)
    {
      if (e.Button == MouseButtons.Left)
      {
        oldLocation = e.Location;
        rect = pic.Bounds;
      }
    }

mouse_move

private void pictureBox_MouseMove(object sender, MouseEventArgs e)
    {
      if (e.Button == MouseButtons.Left)
      {
        isDrag = true;
        rect.Location = getPointToForm(new Point(e.Location.X - oldLocation.X, e.Location.Y - oldLocation.Y));
        this.Refresh();
 
      }
    }

mouse_up

private void pictureBox_MouseUp(object sender, MouseEventArgs e)
    {
      oldLocation = new Point(currentPictureBox.Location.X, currentPictureBox.Location.Y);
      if (oldLocation.X + e.X > 300 || oldLocation.Y + e.Y > 300||oldLocation.X + e.X < 0 || oldLocation.Y + e.Y < 0)
      {
        return;
      }
      haveToPictureBox = GetPictureBoxByLocation(oldLocation.X + e.X, oldLocation.Y + e.Y);
      newLocation = new Point(haveToPictureBox.Location.X, haveToPictureBox.Location.Y);
      haveToPictureBox.Location = oldLocation;
      PictureMouseUp(currentPictureBox, sender, e);
      if ( Judge())
      {
        lab_result.Text = "成功!";
        //MessageBox.Show("恭喜拼图成功");
      }
    }
 
    public void PictureMouseUp(PictureBox pic, object sender, MouseEventArgs e)
    {
      if (e.Button == MouseButtons.Left)
      {
        if (isDrag)
        {
          isDrag = false;
          pic.Location = newLocation;
          this.Refresh();
        }
        reset();
      }
    }

reset

private void reset()
   {
     mouseDownPoint = Point.Empty;
     rect = Rectangle.Empty;
     isDrag = false;
   }

以上所述就是本文的全部内容了,希望大家能够喜欢。

[!--infotagslink--]

相关文章

  • C#实现简单的登录界面

    我们在使用C#做项目的时候,基本上都需要制作登录界面,那么今天我们就来一步步看看,如果简单的实现登录界面呢,本文给出2个例子,由简入难,希望大家能够喜欢。...2020-06-25
  • 浅谈C# 字段和属性

    这篇文章主要介绍了C# 字段和属性的的相关资料,文中示例代码非常详细,供大家参考和学习,感兴趣的朋友可以了解下...2020-11-03
  • C#中截取字符串的的基本方法详解

    这篇文章主要介绍了C#中截取字符串的的基本方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-03
  • C#实现简单的Http请求实例

    这篇文章主要介绍了C#实现简单的Http请求的方法,以实例形式较为详细的分析了C#实现Http请求的具体方法,需要的朋友可以参考下...2020-06-25
  • C#连接SQL数据库和查询数据功能的操作技巧

    本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
  • C#中new的几种用法详解

    本文主要介绍了C#中new的几种用法,具有很好的参考价值,下面跟着小编一起来看下吧...2020-06-25
  • 使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)

    这篇文章主要介绍了使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • C#开发Windows窗体应用程序的简单操作步骤

    这篇文章主要介绍了C#开发Windows窗体应用程序的简单操作步骤,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-04-12
  • C#从数据库读取图片并保存的两种方法

    这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
  • C#和JavaScript实现交互的方法

    最近做一个小项目不可避免的需要前端脚本与后台进行交互。由于是在asp.net中实现,故问题演化成asp.net中jiavascript与后台c#如何进行交互。...2020-06-25
  • C++调用C#的DLL程序实现方法

    本文通过例子,讲述了C++调用C#的DLL程序的方法,作出了以下总结,下面就让我们一起来学习吧。...2020-06-25
  • 轻松学习C#的基础入门

    轻松学习C#的基础入门,了解C#最基本的知识点,C#是一种简洁的,类型安全的一种完全面向对象的开发语言,是Microsoft专门基于.NET Framework平台开发的而量身定做的高级程序设计语言,需要的朋友可以参考下...2020-06-25
  • C#变量命名规则小结

    本文主要介绍了C#变量命名规则小结,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-09
  • C#绘制曲线图的方法

    这篇文章主要介绍了C#绘制曲线图的方法,以完整实例形式较为详细的分析了C#进行曲线绘制的具体步骤与相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • C# 中如何取绝对值函数

    本文主要介绍了C# 中取绝对值的函数。具有很好的参考价值。下面跟着小编一起来看下吧...2020-06-25
  • c#自带缓存使用方法 c#移除清理缓存

    这篇文章主要介绍了c#自带缓存使用方法,包括获取数据缓存、设置数据缓存、移除指定数据缓存等方法,需要的朋友可以参考下...2020-06-25
  • c#中(&&,||)与(&,|)的区别详解

    这篇文章主要介绍了c#中(&&,||)与(&,|)的区别详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
  • 经典实例讲解C#递归算法

    这篇文章主要用实例讲解C#递归算法的概念以及用法,文中代码非常详细,帮助大家更好的参考和学习,感兴趣的朋友可以了解下...2020-06-25
  • C#学习笔记- 随机函数Random()的用法详解

    下面小编就为大家带来一篇C#学习笔记- 随机函数Random()的用法详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • C#中list用法实例

    这篇文章主要介绍了C#中list用法,结合实例形式分析了C#中list排序、运算、转换等常见操作技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25