使用跟踪"d"在该位置的 2D 数组

  • 本文关键字:位置 2D 数组 跟踪 c#
  • 更新时间 :
  • 英文 :


我有一个2d数组,它正在四处移动字符'd',所有不是字符的都有'*'。当移动开始时,所有位置都为零。每次移动时,该位置都会增加1。如何增加每个点的值?我的代码:

using System;
class MainClass {
public static void Main (string[] args) {
bool over = false;

Console.Write("Enter city size: ");
int size = Convert.ToInt32(Console.ReadLine());
char [,] city = new char [size,size];
int [,] counts = new int [size,size];
CreateCity(city);
Console.Clear();
while(!over){
ShowCity(city, counts);        
Move(city, counts, ref over);
System.Threading.Thread.Sleep((int)System.TimeSpan.FromSeconds(1).TotalMilliseconds);
if(!over){
Console.Clear();
Console.WriteLine();}
}//end while
Console.WriteLine("done");
}//end main 
public static void CreateCity(char [,] c){
int rowLength = c.GetLength(0);
int colLength = c.GetLength(1);
for(int i = 0; i < rowLength; i++){
for(int j = 0; j < colLength; j++){
c[i,j] = '*';}//end j
}//end i
c[rowLength/2,colLength/2] = 'D';
}//end CreateCity
public static void ShowCity (char [,] c, int [,] d){
for(int i = 0; i < c.GetLength(0); i++){
for(int j = 0; j < c.GetLength(1); j++){Console.Write("{0}t",c[i,j]);}
Console.WriteLine();
}}//end ShowCity
public static int GetDirection(){
Random random = new Random();  
int num = random.Next(-1,2);
return num;
}
public static void Move (char [,] c, int [,] d, ref bool done){
int alocation = 0;
int bloaction = 0;
int anewLocation = 0;
int bnewlocation = 0;
int asize = c.GetLength(0);
int bsize = c.GetLength(1);

for(int i = 0; i < asize; i++){
for(int j = 0; j < bsize; j++){
if (c[i,j] == 'D'){
alocation = i;
bloaction = j;
}}}

anewLocation = alocation+GetDirection();
bnewlocation = bloaction+GetDirection();
if (( anewLocation == -1 || anewLocation == asize ) || ( bnewlocation == -1 || bnewlocation == bsize )){
done = true; 
}//bounds if
else{
c[alocation,bloaction] = '*';
c[anewLocation,bnewlocation] = 'D';

}
}
}//end  class

产生

*   *   *   *   *
*   *   *   *   D
*   *   *   *   *
*   *   *   *   *
*   *   *   *   *

D从中间开始移动,所以我希望它能产生

*   *   *   *   *
*   *   *   1   D
*   *   1   2   1
*   *   *   1   1
*   *   *   *   *

因此,如果D移动一次,它就变为1。我有int [,] counts = new int [size,size];来保存我将用于数字的值,但我希望在如何进行方面得到帮助

Move()方法应该更改为类似于以下内容:

else
{
d[alocation, bloaction]++;
string countStr = d[alocation, bloaction].ToString();
c[alocation, bloaction] = countStr[countStr.Length - 1];
c[anewLocation, bnewlocation] = 'D';
}
}
}//end  class

我使用countStr[countStr.Length - 1]是因为城市单元格是字符,不能容纳整个字符串。我认为你最好用string[,]而不是char[,]

最新更新