Haber - Bilgi Paylasımı

hbrf2

Visual C#.NET ile Labirent Uygulaması


Labirent bir grid (matris) şeklinde tasarlanacak; labirentin ebatlarını ve iç değerlerini bir input dosyasından okuyacaksınız. Input dosyasının ilk satırı boyutları verecek, ikinci satır labirente giriş noktasını, üçüncü satırda labirentten çıkış noktasını, dördüncü satırdan itibaren de labirentin değerlerini okuyacaksınız. Input dosyasının ismi odvinp.txt olacak...



Visual C#.NET ile Labirent Uygulaması

PROBLEM

Bir labirent uygulaması yazacaksınız. Labirent bir grid (matris) şeklinde tasarlanacak; labirentin ebatlarını ve iç değerlerini bir input dosyasından okuyacaksınız. Input dosyasının ilk satırı boyutları verecek, ikinci satır labirente giriş noktasını, üçüncü satırda labirentten çıkış noktasını, dördüncü satırdan itibaren de labirentin değerlerini okuyacaksınız. Input dosyasının ismi odvinp.txt olacak. Odvinp.txt ye örnek verecek olursak: 5-5 lik bir labirentte, giriş noktasının 2. satır, 1. sütun ve çıkış noktasının 5.satır 4. sütun olduğunu varsayarsak. (Bu gösterimde 1leri duvar yada dolu, 0larıda boş ve gezinebilir varsayıyoruz.)

5,5
2,1
5,4
1 0 0 0 1
0 0 1 0 1
0 0 1 0 0
1 0 1 0 1
1 1 0 0 1

Labirentte hareket yönleri yukarı-sağ-sol-aşağı yönleridir, çapraz hareket edilemeyecektir. Giriş noktasından başlayarak çıkış noktası yakalanmaya çalışılacak ve böyle bir güzergah bulunabilirse güzergah noktalarını bir text dosyaya yazacaksınız, bu dosyanın ismi okul numaranızın son 4 hanesi.txt şeklinde olacak. Eğer bir güzergah bulunamaz ise bu dosyaya ‘uygun yol bulunamadı' yazılacak. Uygun yolda her nokta sadece 1 kere ziyaret edilmiş olunmalı. Yukarıdaki örneğin çıkış dosyası yan yana veya alt alta yazılı şekilde giriş ve çıkış noktalarıyla birlikte 2,1 2,2 1,2 1,3 1,4 2,4 3,4 4,4 5,4 şeklinde olacak.

Zip'li dosyayı indirmek için tıklayın.

KAYNAK KODLAR


/// 
/// Sonuca giden asil yolu tutan sinif
/// mys isimli sinifimda tanimladigim alar arraylist inde tutuluyor.
/// 
public class actualRoad
{
	public Point p;	
	public actualRoad(Point P)
	{
		p = P;
	}
}


/// 
/// Labirentin 1 ve 0 larini tutan yapim
/// 
public struct myarr
{
	public Int16 val;
	public bool visited;
	public myarr(Int16 Val, bool V)
	{
        val = Val;
		visited = V;
	}

}
/// 
/// Bir çok islemi ve fonksiyonlari yaptigim sinifim
/// 
public class mys
{
	private Point current; // üstünde bulunulan nokta
	private Point endP;    // labirentin çikis noktasi
	private int row,col;   // labirent kaç satir ve sutündan olusuyor.
	private int[] bestway = new int[4];	// ilerleme için en iyi nasildir.
	public ArrayList alAR = new ArrayList();// çikisa giden asil yol. actualroad isimli sinif
	public myarr[,] myArr; // labirentin 1 ve sifirlarini tutan degisken
	public Stack stack; // birden fazlama ilerleme yönü oldugunda o noktayi tutan yigin
	
	/// 
	/// Row getter i
	/// 
	public int Row
	{
		get
		{
			return row;
		}
	}
	/// 
	/// Col getter i
	/// 
	public int Col
	{
		get
		{
			return col;
		}
	}
	/// 
	/// mevcut nokta getter ve setter i
	/// 
	public Point Current
	{
		get
		{
			return current;
		}
		set
		{
			current = value;				
		}
	} // end of point current

	/// 
	/// son nokta getter ve setter i
	/// 
	public Point EndP
	{
		get
		{
			return endP;
		}            
		set
		{
			endP = value;
		}
	} // end of EndP

	/// 
	/// boyutlarin atandigi method.
	/// 		
	public void setLength(int Row,int Col)
	{
		stack = new Stack();
		row = Row-1;
		col = Col-1;
		myArr = new myarr[Row,Col];
	}

	/// 
	/// Tarama isleminde en iyi yönü belirleyen method.
	/// 
	public void findBestWay()
	{
		if ((current.X <= endP.X)&&(current.Y <= endP.Y))
		{
			bestway[0] = 1;
			bestway[1] = 2;
			bestway[2] = 3;
			bestway[3] = 4;
		} 
		else if ((current.X >= endP.X)&&(current.Y <= endP.Y))
		{
			bestway[0] = 1;
			bestway[1] = 4;
			bestway[2] = 3;
			bestway[3] = 2;
		}
		else if ((current.X <= endP.X)&&(current.Y >= endP.Y))
		{
			bestway[0] = 3;
			bestway[1] = 2;
			bestway[2] = 1;
			bestway[3] = 4;
		}
		else if ((current.X >= endP.X)&&(current.Y >= endP.Y))
		{
			bestway[0] = 3;
			bestway[1] = 4;
			bestway[2] = 1;
			bestway[3] = 2;
		}
	}

	/// 
	/// actual road a ekleme islemini yapan method
	/// 
	/// eklenecek nokta
	public void addAR(Point p)
	{			
		alAR.Add(new actualRoad(p));
	}

	/// 
	/// actual road tan silme islemini yapan method
	/// 		
	public void removeAR()
	{
		alAR.RemoveAt(alAR.Count-1);
	}

	/// 
	/// üstünde bulunulan noktayi gidildi yapiyor. Birdaha gitmemek için
	/// 
	public void makeVisited()
	{
		myArr[current.X,current.Y].visited = true;
	}

	/// 
	/// Noktanin duvarmi degilmi oldugunu belirliyor.
	/// 
	/// kontrol edilecek nokta
	/// boolean sonuc
	public bool isitWall(Point p)
	{
		if (myArr[p.X,p.Y].val==1)
			return true;
		else
			return false;
	}

    /// 
    /// stackten deger okuyor. Tikanma durumlarinda çalisiyor.
    /// 
    /// 1=nokta var.0=stackte deger yok.Çikisada gidilemedi.
	public byte readStack()
	{
		if (stack.Count>0)
		{
			current = ((Point)stack.Pop());
			return 1;
		}
		else
			return 0;
	}

	/// 
	/// Üstünde bulunulan nokta son nokta mi
	/// 
	/// sayac
	/// x yönü
	/// y yönü
	/// 2=evet çikis.1=hayir devam et aramaya
	public byte isitFinal(sbyte cnt,sbyte wayX,sbyte wayY)
	{
		if (cnt>1)
			stack.Push(current);			
		current = new Point(current.X+wayX , current.Y+wayY);
		addAR(current);
		makeVisited();
		if (current == endP)
			return 2;
		else
			return 1;
	}
	

	/// 
	/// üstünde bulunulan noktanin etrafina bakiyor.
	/// 
	/// gidilecek yönü belirliyor.
	/// x yönü
	/// y yönü
	/// sayici
	public void lookAtSides(out sbyte way,out sbyte wayX,out sbyte wayY,out sbyte cnt) 
	{
		findBestWay();
		byte i;
		wayX = wayY = cnt = way = 0;	
		for (i=0;i<4;i++)
			switch (bestway[i])
			{
				case 1:
					if ((myArr[current.X,current.Y+1].val==0)&&(!myArr[current.X,current.Y+1].visited))
					{
						if ((wayY==0)&&(wayX==0))
						{
							wayY = 1;
							way = 1;
						}
						cnt++;
					}
					break;
				case 2:
					if ((myArr[current.X+1,current.Y].val==0)&&(!myArr[current.X+1,current.Y].visited))
					{
						if ((wayY==0)&&(wayX==0))
						{
							wayX = 1;
							way = 2;
						}
						cnt++;
					}
					break;
				case 3:
					if ((myArr[current.X,current.Y-1].val==0)&&(!myArr[current.X,current.Y-1].visited))
					{
						if ((wayY==0)&&(wayX==0))
						{
							wayY = -1;
							way = 3;
						}
						cnt++;
					}
					break;
				case 4:
					if ((myArr[current.X-1,current.Y].val==0)&&(!myArr[current.X-1,current.Y].visited))
					{
						if ((wayY==0)&&(wayX==0))
						{
							wayX = -1;
							way = 4;
						}
						cnt++;
					}			
					break;
			}			
	}
}


	

//// yukarıdaki kodlar kullandıımız sınıfın kodları idi
/// şimdi de form kısmında yazdıımız kodlara bakalım.

	/// 
	/// Summary description for Form1.
	/// 
	public class frmLabirent : System.Windows.Forms.Form
	{
		public int x,y;
		private TextureBrush tbWall;
		private TextureBrush tbRoad;	
		private TextureBrush tbR,tbL,tbU,tbD,tbS,tbF;
		private mys myS;
		[STAThread]
		static void Main() 
		{
			Application.Run(new frmLabirent());
		}


/// 
/// Okunan matrisin etrafini birlerle çevirmek için kullaniliyor.
/// 
public void surroundbyWall()
{
	int i;
	for (i=0;i<=myS.Col;i++)	
	{
		myS.myArr[0,i].val=myS.myArr[myS.Row,i].val=1;
	}
	for (i=0;i<=myS.Row;i++)			
		myS.myArr[i,0].val=myS.myArr[i,myS.Col].val=1;
}

/// 
/// Ilk üç satirda bilgileri okumak için yazilan method
/// 
/// gelen string
/// hangi satir
public void assignParam(string str,int type)
{
    int x , y;
	int i = str.IndexOf(",");
	x = Int32.Parse(str.Substring(0,i));
	y = Int32.Parse(str.Substring(i+1,str.Length-i-1));
	Point p = new Point(x,y);
	if (type==0) // set length
	{
		bmp = new Bitmap(y*20,x*20);
		lblSize.Text = x.ToString()+","+y.ToString();
		myS.setLength(x+2,y+2); 				
	}
	else if (type==1) // start point
	{
		myS.Current = p;
		lblSP.Text = p.X.ToString()+","+p.Y.ToString();				
	}
	else if (type==2) // end point
	{
		myS.EndP = p;				
		lblEP.Text = p.X.ToString()+","+p.Y.ToString();				
	}
}

/// 
/// Kontrol isleminin yapilmasi. Baslangiç ve bitis noktasi
/// duvar olmasin vs.
/// 
public void controlP()
{			
	if (myS.isitWall(myS.Current))
	{
		lblMsg.Text = "A wall cannot be a starting point !!! Rearrange the file";
		btnFind.Enabled = false;
	}
	else if (myS.isitWall(myS.EndP))
	{
		lblMsg.Text = "A wall cannot be a ending point !!! Rearrange the file";
		btnFind.Enabled = false;
	}
	else
	{
		lblMsg.Text = "You can now click the "FIND A R.." button.";				
		btnFind.Enabled = true;
	}
}

/// 
/// Text dosyasiyi okuyarak myArr isimli diziye atiyan ve
/// birlere ve sifirlara göre resmi olusturan method
/// 		
private void btnLoad_Click(object sender, System.EventArgs e)
{
	int row,col,i;
	row = col =  i =  0;		
	StreamReader rdr = new StreamReader(Directory.GetCurrentDirectory()+"/Odvinp.txt");		
	
	myS = new mys();				
	
	assignParam(rdr.ReadLine(),0);
	pBox.Width = bmp.Width;
	pBox.Height = bmp.Height;
	Graphics myGO = Graphics.FromImage(bmp);
	
	assignParam(rdr.ReadLine(),1);
	assignParam(rdr.ReadLine(),2);			
	
	surroundbyWall();
	bool enter = false;
	string line;
	while ((line = rdr.ReadLine())!=null)
	{
		i = col =0;					
		while (i<line.Length)
		{
			enter = false;
			if (line[i].ToString()!=" ")
			{
				Region myReg = new Region(new Rectangle(col*20,row*20,(col+1)*20,(row+1)*20));
				if (line[i].ToString()=="1")
				{		
					myGO.FillRegion(tbWall,myReg);
					myS.myArr[row+1,col+1].val = 1;
					enter = true;
				}
				else if (line[i].ToString()=="0")
				{
					myGO.FillRegion(tbRoad,myReg);
					myS.myArr[row+1,col+1].val = 0;
					enter = true;
				}
				if (enter)
				{
					col++;
					if (col>myS.Col-2)
						break;
				}
			}	
			i++;
		}										
		row++;	
		if (row>myS.Row-2)
			break;
	}// end of while	
	rdr.Close();
	controlP();
	myGO.DrawImage(bmp,0,0);
	pBox.Image = bmp;						
}

/// 
/// Tarama isleminde ilerledikçe resmide es zamanli olarak 
/// boyamak için kullanilan method.
/// 
/// hangi texture ile boyanacak.
/// hangi nokta boyanacak
private void copyPortion(sbyte way,Point p)
{
	Graphics myGO = Graphics.FromImage(bmp);
	Rectangle rect = new Rectangle((p.Y-1)*20,(p.X-1)*20,20,20);
	Region myReg = new Region(rect);
	switch (way)
	{
		case 1:
			myGO.FillRegion(tbR,myReg);
			break;
		case 2:
			myGO.FillRegion(tbD,myReg);
			break;
		case 3:
			myGO.FillRegion(tbL,myReg);
			break;
		case 4:
			myGO.FillRegion(tbU,myReg);
			break;
		case 5:
			myGO.FillRegion(tbS,myReg);
			break;
		case 6:
			myGO.FillRegion(tbF,myReg);
			break;
	}
	myGO.DrawImage(bmp,0,0);			
	pBox.Image = bmp;
}


private void pBox_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
	x = e.X / 20;
	y = e.Y / 20;		
}

private void startP_Click(object sender, System.EventArgs e)
{
	lblSP.Text = x.ToString()+" , "+y.ToString();			
}

private void endP_Click(object sender, System.EventArgs e)
{
    lblEP.Text = x.ToString()+" , "+y.ToString();
}		

/// 
/// Formun yüklenmesinde resmi boyamak için gereken
/// alt küçük resimleri yüklüyorum.
/// 		
private void Form1_Load(object sender, System.EventArgs e)
{
	tbWall	= new TextureBrush(new Bitmap(Directory.GetCurrentDirectory()+"/1.bmp"));
	tbRoad	= new TextureBrush(new Bitmap(Directory.GetCurrentDirectory()+"/0.bmp"));					
	tbR		= new TextureBrush(new Bitmap(Directory.GetCurrentDirectory()+"/rigth.bmp"));	
	tbL		= new TextureBrush(new Bitmap(Directory.GetCurrentDirectory()+"/left.bmp"));	
	tbU		= new TextureBrush(new Bitmap(Directory.GetCurrentDirectory()+"/up.bmp"));	
	tbD		= new TextureBrush(new Bitmap(Directory.GetCurrentDirectory()+"/down.bmp"));	
	tbS		= new TextureBrush(new Bitmap(Directory.GetCurrentDirectory()+"/stop.bmp"));
	tbF		= new TextureBrush(new Bitmap(Directory.GetCurrentDirectory()+"/finish.bmp"));	
}

/// 
/// label ve picture box i güncellemek için
/// 
public void update2()
{
	lblXY.Update();
	pBox.Update();
}
/// 
/// Taram isleminin baslangiç noktasi
/// 

private void btnFind_Click(object sender, System.EventArgs e)
{
	btnFind.Enabled = false;
	sbyte wayX,wayY,way,cnt;			
	byte goOn = 1;
	// goOn=1-> go on searching, 
	// goOn=0-> there is no way to the end
	// goOn=2-> ok, found it.
	myS.makeVisited();
	myS.addAR(myS.Current);
	while (goOn==1)
	{
        myS.lookAtSides(out way,out wayX, out wayY,out cnt);    
		if (cnt == 0)
		{
			goOn = myS.readStack();
			if (goOn==1)
				while (myS.Current != ((actualRoad)myS.alAR[myS.alAR.Count-1]).p)
				{
                    copyPortion(5,((actualRoad)myS.alAR[myS.alAR.Count-1]).p);
					myS.removeAR();	
					System.Threading.Thread.Sleep(250);
					update2();
					lblXY.Text = myS.Current.X.ToString()+","+myS.Current.Y.ToString();
				}					
		}
		else
		{
			copyPortion(way,myS.Current);
			goOn = myS.isitFinal(cnt,wayX,wayY);					
		}
		lblXY.Text = myS.Current.X.ToString()+","+myS.Current.Y.ToString();
		System.Threading.Thread.Sleep(250);
		update2();
	}
	StreamWriter sr = File.CreateText(Directory.GetCurrentDirectory()+"/5051.txt");
	if (goOn==2)
	{
		copyPortion(6,myS.Current);					
		for (int i = 0;i<myS.alAR.Count;i++)
			sr.WriteLine(((actualRoad)myS.alAR[i]).p.ToString());				
		lblMsg.Text = "A road is found.The direction is in the 5051.txt file.";
	}
	else if (goOn==0)
	{
		lblMsg.Text = "THERE IS NO A ROAD TO THE END POINT !!!";
		sr.WriteLine(lblMsg.Text);				
	}
	sr.WriteLine("--");
	sr.WriteLine("5051 Mesut GÜRBÜZ");
	sr.Close();

}
Kaynak:TeknoHaber
Bugün 8 ziyaretçi (27 klik) kişi burdaydı!

Bu web sitesi ücretsiz olarak Bedava-Sitem.com ile oluşturulmuştur. Siz de kendi web sitenizi kurmak ister misiniz?
Ücretsiz kaydol