热门标签 | HotTags
当前位置:  开发笔记 > 开发工具 > 正文

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

这篇文章主要介绍了C#利用控件拖拽技术制作拼图游戏的方法以及核心代码,需要的朋友可以参考下

主要实现的功能:

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 pictureLocatiOnDict= new SortedDictionary();
    //Location List 
    Point[] pointList = null;
    //图片控件字典
    SortedDictionary pictureBoxLocatiOnDict= new SortedDictionary();
    //拼图时间
    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();
    }
 
    /// 
    /// 初始化游戏资源
    /// 
    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);
        }
      }
    }
 
   
    /// 
    /// 不好用
    /// 
    /// 
    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;
    }
 
    /// 
    /// 通过hashcode获取picture,用mouseeventargs之后获取相对于picture的坐标不是相对窗体
    /// 
    /// 
    /// 
    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);
    }
 
    /// 
    /// 初始化
    /// 
    /// 
    public void Flow(string path)
    {
      Image bm = CutPicture.Resize(path, 300, 300);
      CutPicture.BitMapList = new List();
      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();
    }
 
    /// 
    /// 打乱数据
    /// 
    /// 
    /// 
    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;
    }
 
    /// 
    /// 判断是否拼图成功
    /// 
    /// 
    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();
    }
 
    /// 
    /// 计时
    /// 
    public void CountTime()
    {
      lab_time.Text = "0";
      timer1.Start();
    }
 
    /// 
    /// 给piturebox赋值
    /// 
    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);
      }
       
    }
 
    /// 
    /// 打乱位置列表
    /// 
    /// 
    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;
    }
 
    /// 
    /// 重新设置图片位置
    /// 
    public void ResetPictureLocation()
    {
      Point[] temp = DisOrderLocation();
      int i = 0;
      foreach (PictureBox item in pictureList)
      {
        item.Location = temp[i];
        i++;
      }
    }
 
    /// 
    /// 计时,超过30秒停止计时
    /// 
    /// 
    /// 
    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

&#65279;
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 BitMapList = null;
    /// 
    /// 剪切图片
    /// 
    /// 图片
    /// X坐标
    /// Y坐标
    /// 宽
    /// 高
    /// 
    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;
      }
    }
 
    /// 
    /// 保存图片到根目录的Pictures文件夹下
    /// 
    /// 文件路径
    /// 调整的宽
    /// 调整的高
    /// 
    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;
   }

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


推荐阅读
  • 基于layUI的图片上传前预览功能的2种实现方式
    本文介绍了基于layUI的图片上传前预览功能的两种实现方式:一种是使用blob+FileReader,另一种是使用layUI自带的参数。通过选择文件后点击文件名,在页面中间弹窗内预览图片。其中,layUI自带的参数实现了图片预览功能。该功能依赖于layUI的上传模块,并使用了blob和FileReader来读取本地文件并获取图像的base64编码。点击文件名时会执行See()函数。摘要长度为169字。 ... [详细]
  • 搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的详细步骤
    本文详细介绍了搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的步骤,包括环境说明、相关软件下载的地址以及所需的插件下载地址。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 本文介绍了C#中生成随机数的三种方法,并分析了其中存在的问题。首先介绍了使用Random类生成随机数的默认方法,但在高并发情况下可能会出现重复的情况。接着通过循环生成了一系列随机数,进一步突显了这个问题。文章指出,随机数生成在任何编程语言中都是必备的功能,但Random类生成的随机数并不可靠。最后,提出了需要寻找其他可靠的随机数生成方法的建议。 ... [详细]
  • 本文介绍了在Hibernate配置lazy=false时无法加载数据的问题,通过采用OpenSessionInView模式和修改数据库服务器版本解决了该问题。详细描述了问题的出现和解决过程,包括运行环境和数据库的配置信息。 ... [详细]
  • Win10下游戏不能全屏的解决方法及兼容游戏列表
    本文介绍了Win10下游戏不能全屏的解决方法,包括修改注册表默认值和查看兼容游戏列表。同时提供了部分已经支持Win10的热门游戏列表,帮助玩家解决游戏不能全屏的问题。 ... [详细]
  • 如何在联想win10专业版中修改账户名称
    本文介绍了在联想win10专业版中修改账户名称的方法,包括在计算机管理中找到要修改的账户,通过重命名来修改登录名和属性来修改显示名称。同时指出了windows10家庭版无法使用此方法的限制。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • Windows下配置PHP5.6的方法及注意事项
    本文介绍了在Windows系统下配置PHP5.6的步骤及注意事项,包括下载PHP5.6、解压并配置IIS、添加模块映射、测试等。同时提供了一些常见问题的解决方法,如下载缺失的msvcr110.dll文件等。通过本文的指导,读者可以轻松地在Windows系统下配置PHP5.6,并解决一些常见的配置问题。 ... [详细]
  • 电脑公司win7剪切板位置及使用方法
    本文介绍了电脑公司win7剪切板的位置和使用方法。剪切板一般位于c:\windows\system32目录,程序名为clipbrd.exe。通过在搜索栏中输入cmd打开命令提示符窗口,并输入clip /?即可调用剪贴板查看器。赶紧来试试看吧!更多精彩文章请关注本站。 ... [详细]
  • Metasploit攻击渗透实践
    本文介绍了Metasploit攻击渗透实践的内容和要求,包括主动攻击、针对浏览器和客户端的攻击,以及成功应用辅助模块的实践过程。其中涉及使用Hydra在不知道密码的情况下攻击metsploit2靶机获取密码,以及攻击浏览器中的tomcat服务的具体步骤。同时还讲解了爆破密码的方法和设置攻击目标主机的相关参数。 ... [详细]
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • win10系统搭建Java开发环境的操作方法
    本文介绍了win10系统搭建Java开发环境的详细操作方法,包括下载Windows10系统和Java SE,安装Java开发环境,设置变量等步骤。操作简单,只需按照指导进行即可。 ... [详细]
author-avatar
mindylee
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有