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<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;
   }

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

(0)

相关推荐

  • C#在Unity游戏开发中进行多线程编程的方法

    在这之前,有很多人在质疑Unity支不支持多线程,事实上Unity是支持多线程的.而提到多线程就要提到Unity非常常用的协程,然而协程并非真正的多线程.协程其实是等某个操作完成之后再执行后面的代码,或者说是控制代码在特定的时机执行.而多线程在Unity渲染和复杂逻辑运算时可以高效的使用多核CPU,帮助程序可以更高效的运行.本篇主要介绍在Unity中如何使用多线程. 首先引入C#中使用多线程的类库 using System.Threading; 创建线程实例的四种方式 一.线程执行无参方法 构造

  • C#拼图游戏编写代码(2)

    前言:在C#拼图游戏编写代码程序设计 之 C#实现<拼图游戏>(上),上传了各模块代码,而在本文中将详细剖析原理,使读者更容易理解并学习,程序有诸多问题,欢迎指出,共同学习成长! 正文: 拼图是一个非常经典的游戏,基本每个人都知道他的玩法,他的开始,运行,结束.那么,当我们想要做拼图的时候如何入手呢?答案是:从现实出发,去描述需求(尽量描述为文档),当我们拥有了全面的需求,就能够提供可靠的策略,从而在代码中实现,最终成为作品! (一)需求: (这个需求书写较为潦草,为广大小白定制,按照最最最普

  • C#实现洗牌游戏实例

    棋牌类游戏是目前比较火的游戏之一.今天本文就以实例形式实现洗牌游戏.本文实例所采用的算法是:遍历每个位置上的牌,然后与随机位置上的牌交换. 运行结果如下图所示: 对于牌来讲,2个关键的因素是面值和类型(如红桃.梅花等). 代码如下: public class Card { private string mianzhi; private string leixin; public Card(string m, string l) { mianzhi = m; leixin = l; } publi

  • C#面向对象编程之猜拳游戏实现方法

    本文实例讲述了C#面向对象编程之猜拳游戏实现方法.分享给大家供大家参考.具体实现方法如下: 1.需求 现在要制作一个游戏,玩家与计算机进行猜拳游戏,玩家出拳,计算机出拳,计算机自动判断输赢. 2.需求分析 根据需求,来分析一下对象,可分析出:玩家对象(Player).计算机对象(Computer).裁判对象(Judge). 玩家出拳由用户控制,使用数字代表:1石头.2剪子.3布 计算机出拳由计算机随机产生 裁判根据玩家与计算机的出拳情况进行判断输赢. 3.类对象的实现 ①.玩家类示例代码: 复制

  • C#实现的算24点游戏算法实例分析

    本文实例讲述了C#实现的算24点游戏算法.分享给大家供大家参考.具体如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Calc24Points { public class Cell { public enum Type { Number, Signal } public int Number; public ch

  • C#十五子游戏编写代码

    本文实例为大家分享了C#十五子游戏的具体代码,供大家参考,具体内容如下 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms;

  • C#拼图游戏编写代码

    本文设计了C#拼图游戏程序,供大家参考,具体内容如下 功能描述: 1.用户自定义上传图片 2.游戏难度选择:简单(3*3).一般(5*5).困难(9*9)三个级别 3.纪录完成步数 模块: 1.拼图类 2.配置类 3.游戏菜单窗口 4.游戏运行窗口 代码文件VS2013版本: 下载链接: 拼图游戏 --------------------------------------------------我叫分割线---------------------------------------------

  • 基于C#实现俄罗斯方块游戏

    最近在看C#,写了一个很水的方块游戏练手. 代码: namespace game { class Square { public Square() { state = 0; positionY = 0; positionX = 0; } public Square(int InitShapeCnt, int InitState) { state = InitState; positionY = 0; positionX = 0; InitShape(InitShapeCnt); } public

  • C#实现的24点游戏实例详解

    本文实例分析了C#实现的24点游戏.分享给大家供大家参考.具体如下: 1. 24点游戏规则及算法 规则:给出4个自然数,找出能够求出24的四则运算式,要求数字不能重复使用 分析: 本算法是一种暴力求解法: 给出任意两个数字,可以进行6种四则运算,求出最多6个值.以数字a和b为例,有: 加(a+b).减(a-b).被减(b-a).乘以(a*b).除以(a/b)和除(b/a) abcd共计四个数,如果顺序固定,则有5种计算顺序(★代表上面6种四则运算中的一种): ((a★b)★c)★d.(a★b)★

  • C#实现简单的井字游戏实例

    本文实例讲述了C#实现简单的井字游戏.分享给大家供大家参考.具体如下: /* * Created using: SharpDevelop * Created by: Tony Misner * Date: 1/2/2007 * Time: 2:34 PM * */ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace TicTacToe

随机推荐