上学期程序是设计实验之二,用c#实现一个拼图游戏
(一)需求:(这个需求书写较为简单)
- 图片:有图
- 切割:拼图不是一个图,我们需要把一个整图它切割成N*N的小图
- 打乱:把这N*N的小图打乱顺序,才能叫拼图qwq
- 判断:判断拼图是否成功
- 交互:选择鼠标点击拖动的方式
- 展示原图:拼不出来可以看看
- 更换图片:腻了可以从本地选择一张你喜欢的来拼图
- 选择难度:除了2×2还可以选择切割成3×3或者4×4,看你喜欢qwq
(二)设计:
- 使用VS的c#来实现
- 界面设计:picturebox控件来显示图片,button控件来实现按钮点击的各类事件:图片重排、换图、查看原图等,使用numericUpDown控件来控制切割的边数。如下图:
- 把要拼的图片放进resource文件里
- 设计函数,使用cutpicture类来切割图片
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
namespace 拼图游戏
{
class CutPicture
{
public static string picturePath = "";
public static List<Bitmap> BitMapList = null;
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;
}
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;
}
}
}
}
- Form_Main函数为主函数
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;
using System.IO;
namespace 拼图游戏
{
public partial class Form_Main : Form
{
PictureBox[] picturelist = null;
SortedDictionary&l