拼图游戏
前言
C#实践开发_Winform 系列第八篇:拼图游戏,掌握Graphics类的使用方法,进一步熟悉pictureBox、openFileDialog、statusStrip等控件。一、结果呈现
1. 界面设计
窗体界面设计:openFileDialog控件、StatusStrip控件、ToolStripStatusLabel控件(text内容为“用鼠标单击任意两个图片即可进行图片的对调”)、PictureBox控件(显示图片)、ComboBox控件(分割数选项)、label控件、两个button控件(载入图片、开始按键)2. 运行结果呈现
二、源码
1.Form.cs
代码如下(示例):
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;
using System.Collections;
namespace test5
{
public partial class Form2 : Form
{
public PictureBox[] PicBlock = new PictureBox[25];
int GameSize; //布局大小即行列数
int MAP_WIDTH = 300; //图片宽度
int FirstBlock, SecondBlock;
bool flag; //是否交换
int[] Position = new int[25]; //存放图片序号的数组
Bitmap Source; //生成300X300的像素原图
string filename; //所选择的文件名
public Form2()
{
InitializeComponent();
}
//将原图片经伸缩变换后保存到source位图对象
private void SaveBmp()
{
Graphics g;
g = Graphics.FromImage(Source); //生成Graphics对象
g.DrawImage(Image.FromFile(filename), 0, 0, MAP_WIDTH, MAP_WIDTH); //按MAP_WIDTH* MAP_WIDTH大小保存
}
//初始化游戏过程Initial()
private void init(int n)
{
//数组Position存放图片序号
int t = 0;
Random rdm = new Random();
ArrayList al = new ArrayList();
while (al.Count < n * n)
{
t = rdm.Next(0, n * n);
if ((!al.Contains(t)))
{
al.Add(t);
}
}
for (t = 0; t < al.Count; t++)
{
Position[t] = Convert.ToInt16(al[t]);
}
}
//“分割数”组合框初始化游戏相关设置
public void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
GameSize = (int)Math.Sqrt(Convert.ToInt16(comboBox1.Text));
init(GameSize);
}
//完成Position数组元素和图片拼块的交换
private void swap(object sender, System.EventArgs e)
{
PictureBox bClick = (PictureBox)sender;
int i = 0;
Image temp;
if (flag == false)
{
flag = true;
FirstBlock = Convert.ToInt16(bClick.Tag);
}
else
{
//this.Text = "";
SecondBlock = Convert.ToInt16(bClick.Tag);
temp = PicBlock[SecondBlock].Image;
PicBlock[SecondBlock].Image = PicBlock[FirstBlock].Image;
PicBlock[FirstBlock].Image = temp;
flag = false;
i = Position[SecondBlock]; //图片交换
Position[SecondBlock] = Position[FirstBlock]