백엔드 개발 C#.Net 튜토리얼 C#에서 직소 퍼즐을 작성하기 위한 그래픽 및 텍스트 코드 공유(1부)

C#에서 직소 퍼즐을 작성하기 위한 그래픽 및 텍스트 코드 공유(1부)

Apr 18, 2017 am 09:10 AM
c# 퍼즐 게임

这篇文章主要为大家详细介绍了C#拼图游戏的编写代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文设计了C#拼图游戏程序,供大家参考,具体内容如下

功能描述:

  1.用户自定义上传图片

  2.游戏难度选择:简单(3*3)、一般(5*5)、困难(9*9)三个级别

  3.纪录完成步数

模块:

  1.拼图类

  2.配置类

  3.游戏菜单窗口

  4.游戏运行窗口

 代码文件VS2013版本:

下载链接: 拼图游戏

--------------------------------------------------我叫分割线---------------------------------------------------------------

1.拼图类

方法:

  1.构造函数:传图片并分割成一个一个小图片

  2.交换方法

  3.大图中截取小单元方法

  4.移动单元的方法

  5.打乱单元顺序方法

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 拼图
{
 public class Puzzle
 {
 public enum Diff //游戏难度
 {
 simple,//简单
 ordinary,//普通
 difficulty//困难
 }
 private struct Node //拼图单元格结构体
 {
 public Image Img;
 public int Num;
 }
 private Image _img; //拼图图片
 public int Width; //拼图边长
 private Diff _gameDif; //游戏难度
 private Node[,] node; //单元格数组
 public int N; //单元格数组行列数

 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="Img">拼图大图</param>
 /// <param name="GameDif">游戏难度,该类下结构体Diff</param>
 public Puzzle(Image Img,int Width, Diff GameDif)
 {
 this._gameDif = GameDif;
 this._img = Img;
 this.Width = Width;
 switch(this._gameDif)
 {
 case Diff.simple:    //简单则单元格数组保存为3*3的二维数组
  this.N = 3;
  node=new Node[3,3];
  break;
 case Diff.ordinary:   //一般则为5*5
  this.N = 5;
  node = new Node[5, 5];
  break;
 case Diff.difficulty:  //困难则为9*9
  this.N = 9;
  node = new Node[9, 9];
  break;
 }
 
 //分割图片形成各单元保存在数组中
 int Count = 0;
 for (int x = 0; x < this.N; x++)
 {
 for (int y = 0; y < this.N; y++)
 {

  node[x, y].Img = CaptureImage(this._img, this.Width / this.N, this.Width / this.N, x * (this.Width / this.N), y * (this.Width / this.N));
  node[x, y].Num = Count;
  Count++;
 }
 }
 
 for (int x = 0; x < this.N; x++)
 {
 for (int y = 0; y < this.N; y++)
 {

  Graphics newGra = Graphics.FromImage(node[x, y].Img);
  newGra.DrawLine(new Pen(Color.White), new Point(0, 0), new Point(0, this.Width / this.N));
  newGra.DrawLine(new Pen(Color.White), new Point(0, 0), new Point(this.Width / this.N, 0));
  newGra.DrawLine(new Pen(Color.White), new Point(this.Width / this.N, this.Width / this.N), new Point(this.Width / this.N, 0));
  newGra.DrawLine(new Pen(Color.White), new Point(this.Width / this.N, this.Width / this.N), new Point(0,this.Width / this.N));
 }
 }
 //(最后一项为空单独处理)
 node[N - 1, N - 1].Img = Image.FromFile("Image\\end.PNG");
 Graphics newGra2 = Graphics.FromImage(node[N - 1, N - 1].Img);
 newGra2.DrawLine(new Pen(Color.Red), new Point(1, 1), new Point(1, this.Width / this.N - 1));
 newGra2.DrawLine(new Pen(Color.Red), new Point(1, 1), new Point(this.Width / this.N - 1, 1));
 newGra2.DrawLine(new Pen(Color.Red), new Point(this.Width / this.N - 1, this.Width / this.N - 1), new Point(this.Width / this.N - 1, 1));
 newGra2.DrawLine(new Pen(Color.Red), new Point(this.Width / this.N - 1, this.Width / this.N - 1), new Point( 1,this.Width / this.N - 1));
 //打乱拼图
 this.Upset();

 }


 /// <summary>
 /// 由图片fromImage中截图并返回
 /// </summary>
 /// <param name="fromImage">原图片</param>
 /// <param name="width">宽</param>
 /// <param name="height">高</param>
 /// <param name="spaceX">起始X坐标</param>
 /// <param name="spaceY">起始Y坐标</param>
 /// <returns></returns>
 public Image CaptureImage(Image fromImage, int width, int height, int spaceX, int spaceY)
 {
 int x = 0;
 int y = 0;
 int sX = fromImage.Width - width;
 int sY = fromImage.Height - height;
 if (sX > 0)
 {
 x = sX > spaceX ? spaceX : sX;
 }
 else
 {
 width = fromImage.Width;
 }
 if (sY > 0)
 {
 y = sY > spaceY ? spaceY : sY;
 }
 else
 {
 height = fromImage.Height;
 }

 //创建新图位图 
 Bitmap bitmap = new Bitmap(width, height);
 //创建作图区域 
 Graphics graphic = Graphics.FromImage(bitmap);
 //截取原图相应区域写入作图区 
 graphic.DrawImage(fromImage, 0, 0, new Rectangle(x, y, width, height), GraphicsUnit.Pixel);
 //从作图区生成新图 
 Image saveImage = Image.FromHbitmap(bitmap.GetHbitmap());
 return saveImage;
 }
 /// <summary>
 /// 移动坐标(x,y)拼图单元
 /// </summary>
 /// <param name="x">拼图单元x坐标</param>
 /// <param name="y">拼图单元y坐标</param>
 public bool Move(int x,int y)
 {
 //MessageBox.Show(" " + node[2, 2].Num);
 if (x + 1 != N && node[x + 1, y].Num == N * N - 1)
 {
 Swap(new Point(x + 1, y), new Point(x, y));
 return true;
 }
 if (y + 1 != N && node[x, y + 1].Num == N * N - 1)
 {
 Swap(new Point(x, y + 1), new Point(x, y));
 return true;
 } 
 if (x - 1 != -1 && node[x - 1, y].Num == N * N - 1)
 {
 Swap(new Point(x - 1, y), new Point(x, y));
 return true;
 } 
 if (y - 1 != -1 && node[x, y - 1].Num == N * N - 1)
 {
 Swap(new Point(x, y - 1), new Point(x, y));
 return true;
 }
 return false;
 
 }
 //交换两个单元格
 private void Swap(Point a, Point b)
 {
 Node temp = new Node();
 temp = this.node[a.X, a.Y];
 this.node[a.X, a.Y] = this.node[b.X, b.Y];
 this.node[b.X, b.Y] = temp;
 }
 public bool Judge()
 {
 int count=0;
 for (int x = 0; x < this.N; x++)
 {
 for (int y = 0; y < this.N; y++)
 {
  if (this.node[x, y].Num != count)
  return false;
  count++;
 }
 }
 return true;
 }
 public Image Display()
 {
 Bitmap bitmap = new Bitmap(this.Width, this.Width);
 //创建作图区域 
 Graphics newGra = Graphics.FromImage(bitmap);
 for (int x = 0; x < this.N; x++)
 for (int y = 0; y < this.N; y++)
  newGra.DrawImage(node[x, y].Img, new Point(x * this.Width / this.N, y * this.Width / this.N));
 return bitmap;
 }
 /// <summary>
 /// 打乱拼图
 /// </summary>
 public void Upset()
 {
 int sum = 100000;
 if (this._gameDif == Diff.simple) sum = 10000;
 //if (this._gameDif == Diff.ordinary) sum = 100000;
 Random ran = new Random();
 for (int i = 0, x = N - 1, y = N - 1; i < sum; i++)
 {
 long tick = DateTime.Now.Ticks;
 ran = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32)|ran.Next());
 switch (ran.Next(0, 4))
 {
  case 0:
  if (x + 1 != N)
  {
  Move(x + 1, y);
  x = x + 1;
  }
  
  break;
  case 1:
  if (y + 1 != N)
  {
  Move(x, y + 1);
  y = y + 1;
  } 
  break;
  case 2:
  if (x - 1 != -1)
  {
  Move(x - 1, y);
  x = x - 1;
  } 
  break;
  case 3:
  if (y - 1 != -1)
  {
  Move(x, y - 1);
  y = y - 1;
  }
  break;
 }

 }
 }

 

 }
}
로그인 후 복사

2、配置类:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 拼图
{
 public static class GamePage
 {
 public static Puzzle.Diff Dif; //游戏难度
 public static Image img; //拼图图案
 }
}
로그인 후 복사

游戏菜单:

通过菜单,上传图片至配置类img,并选择难度上传至配置类Dif,然后拼图对象构造时读取配置


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;

namespace 拼图
{
 public partial class Menu : Form
 {
 public Menu()
 {
 InitializeComponent();
 GamePage.img =Image.FromFile(@"Image\\拼图.jpg");
 Control.CheckForIllegalCrossThreadCalls = false;
 }

 private void button1_Click(object sender, EventArgs e)
 {
 GamePage.Dif = Puzzle.Diff.simple;
 this.Hide();
 Form1 ff = new Form1();
 ff.closefather+=new 拼图.Form1.childclose(this.closethis); 
 ff.Show();
 
 }

 private void button2_Click(object sender, EventArgs e)
 {
 GamePage.Dif = Puzzle.Diff.ordinary;
 this.Hide();
 Form1 ff = new Form1();
 ff.closefather += new 拼图.Form1.childclose(this.closethis); 
 ff.Show();
 
 }

 private void button3_Click(object sender, EventArgs e)
 {
 GamePage.Dif = Puzzle.Diff.difficulty;
 this.Hide();
 Form1 ff = new Form1();
 ff.closefather += new 拼图.Form1.childclose(this.closethis); 
 ff.Show();
 
 }

 public void closethis()
 {
 this.Show();
 }


 private void button4_Click(object sender, EventArgs e)
 {
 OpenFileDialog ofd = new OpenFileDialog();
 ofd.ShowDialog();
 GamePage.img = Image.FromFile(ofd.FileName).GetThumbnailImage(600,600,new Image.GetThumbnailImageAbort(delegate { return false; }), IntPtr.Zero); 

 }
 private void Menu_Load(object sender, EventArgs e)
 {
 }

 }
}
로그인 후 복사

游戏运行窗口:

1.注册鼠标点击事件来获得输入消息

2.显示功能

3.pictureBox1用来展示游戏拼图情况

4.pictureBox2展示完整拼图的缩略图(当鼠标移至pictureBox2时,发送消息,使pictureBox1显示完整拼图)

5.Numlabel来显示移动步数(通过变量Num的累加来计算)


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 拼图
{
 public partial class Form1 : Form
 {
 public Form1()
 {
 InitializeComponent();
 }
 private Puzzle puzzle;
 private int Num=0;
 private Image img;
 private void Form1_Load(object sender, EventArgs e)
 {
 img = GamePage.img;
 pictureBox2.Image = img.GetThumbnailImage(120,120, new Image.GetThumbnailImageAbort(delegate { return false; }), IntPtr.Zero);
 puzzle = new Puzzle(img, 600, GamePage.Dif);
 pictureBox1.Image =puzzle.Display();
 }

 private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
 {
 if (puzzle.Move(e.X / (puzzle.Width / puzzle.N), e.Y / (puzzle.Width / puzzle.N)))
 {
 Num++;
 pictureBox1.Image = puzzle.Display();
 if (puzzle.Judge())
 { 
  if (MessageBox.Show("恭喜过关", "是否重新玩一把", MessageBoxButtons.OKCancel) == DialogResult.OK)
  {
  Num = 0;
  puzzle.Upset();
  pictureBox1.Image = puzzle.Display();
  
  }
  else
  {
  Num = 0;
  closefather();
  this.Close();
  }

 }

 }
 NumLabel.Text = Num.ToString();
 }

 private void pictureBox2_MouseEnter(object sender, EventArgs e)
 {
 pictureBox1.Image = img;
 }

 private void pictureBox2_MouseLeave(object sender, EventArgs e)
 {
 pictureBox1.Image = puzzle.Display();
 }


 private void Form1_FormClosed(object sender, FormClosedEventArgs e)
 {
 closefather();
 }
 public delegate void childclose();
 public event childclose closefather;

 }
}
로그인 후 복사

위 내용은 C#에서 직소 퍼즐을 작성하기 위한 그래픽 및 텍스트 코드 공유(1부)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

C#을 사용한 Active Directory C#을 사용한 Active Directory Sep 03, 2024 pm 03:33 PM

C#을 사용한 Active Directory 가이드. 여기에서는 소개와 구문 및 예제와 함께 C#에서 Active Directory가 작동하는 방식에 대해 설명합니다.

C# 직렬화 C# 직렬화 Sep 03, 2024 pm 03:30 PM

C# 직렬화 가이드. 여기에서는 C# 직렬화 개체의 소개, 단계, 작업 및 예제를 각각 논의합니다.

C#의 난수 생성기 C#의 난수 생성기 Sep 03, 2024 pm 03:34 PM

C#의 난수 생성기 가이드입니다. 여기서는 난수 생성기의 작동 방식, 의사 난수 및 보안 숫자의 개념에 대해 설명합니다.

C# 데이터 그리드 보기 C# 데이터 그리드 보기 Sep 03, 2024 pm 03:32 PM

C# 데이터 그리드 뷰 가이드. 여기서는 SQL 데이터베이스 또는 Excel 파일에서 데이터 그리드 보기를 로드하고 내보내는 방법에 대한 예를 설명합니다.

C#의 팩토리얼 C#의 팩토리얼 Sep 03, 2024 pm 03:34 PM

C#의 팩토리얼 가이드입니다. 여기서는 다양한 예제 및 코드 구현과 함께 C#의 계승에 대한 소개를 논의합니다.

C#의 패턴 C#의 패턴 Sep 03, 2024 pm 03:33 PM

C#의 패턴 가이드. 여기에서는 예제 및 코드 구현과 함께 C#의 패턴 소개 및 상위 3가지 유형에 대해 설명합니다.

C#의 소수 C#의 소수 Sep 03, 2024 pm 03:35 PM

C#의 소수 가이드. 여기서는 코드 구현과 함께 C#의 소수에 대한 소개와 예를 논의합니다.

멀티 스레딩과 비동기 C#의 차이 멀티 스레딩과 비동기 C#의 차이 Apr 03, 2025 pm 02:57 PM

멀티 스레딩과 비동기식의 차이점은 멀티 스레딩이 동시에 여러 스레드를 실행하는 반면, 현재 스레드를 차단하지 않고 비동기식으로 작업을 수행한다는 것입니다. 멀티 스레딩은 컴퓨팅 집약적 인 작업에 사용되며 비동기식은 사용자 상호 작용에 사용됩니다. 멀티 스레딩의 장점은 컴퓨팅 성능을 향상시키는 것이지만 비동기의 장점은 UI 스레드를 차단하지 않는 것입니다. 멀티 스레딩 또는 비동기식을 선택하는 것은 작업의 특성에 따라 다릅니다. 계산 집약적 작업은 멀티 스레딩을 사용하고 외부 리소스와 상호 작용하고 UI 응답 성을 비동기식으로 유지 해야하는 작업을 사용합니다.

See all articles