如何将10 x 10网格对象打印到控制台

时间:2011-11-03 21:51:35

标签: objective-c

我正在制作一个战斗机游戏在控制台中播放 - 你如何NSLog字符串使它们显示为10 x 10网格而不是长列表。每个坐标都是boardArray中的@“X”对象。 理想情况下,我想循环 - 但是,无论如何! 谢谢。

NSMutableArray *boardArray = [[NSMutableArray alloc]initWithCapacity:110];
NSMutableString *blank =[[NSMutableString alloc]initWithString:@"X"];

for (int x = 0; x < 101; x++) {
    [boardArray insertObject:blank atIndex:x];
}


for (int x = 0; x < 100; x++){

    // what goes here to print (NSLog) a 10 x 10 grid of objects
    // each object is a string @"X" from the boardArray.

}

4 个答案:

答案 0 :(得分:3)

快速示例:

// Create Array (01, 02, 03, 04, 05, etc.)

NSMutableArray *theArray = [[NSMutableArray alloc]init];
for (int i = 0; i < 100; i++) {
    [theArray addObject:[NSString stringWithFormat:@"%02d",i]];
}

// Print Array

for (int i = 0; i < 10; i++) {
    NSArray *subArray = [theArray subarrayWithRange:NSMakeRange(0+(i*10),10)];
    NSLog(@"%@",[subArray componentsJoinedByString:@" "]);
}

输出:

00 01 02 03 04 05 06 07 08 09
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 75 76 77 78 79
80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99

答案 1 :(得分:1)

让您的模型与您的结构相匹配对我来说更有意义,例如10 x 10是2维因此使用2D结构。

  NSMutableArray *board = [[NSMutableArray alloc] initWithCapacity:10];
  NSMutableArray *row   = [[NSMutableArray alloc] initWithCapacity:10];

  for (int i = 0; i < 10; i++) {
    [row addObject:@"X"];
  }

  [board addObject:row];

  NSMutableArray *preFilledRow = nil;

  for (int i = 0; i < 9; i++) {
    preFilledRow = [row mutableCopy];
    [board addObject:preFilledRow];
    [preFilledRow release]; preFilledRow = nil;
  }

  [row release]; row = nil;

  for (NSMutableArray *boardRow in board) {
    NSLog(@"%@", [boardRow componentsJoinedByString:@" "]);
  // printf("%s\n", [[boardRow componentsJoinedByString:@" "] UTF8String]); <- Use this if you don't want additional info printed
  }

  [board release]; board = nil;

答案 2 :(得分:0)

你需要查看NSMutableString类来构造你的字符串然后显示在你的NSLog()

答案 3 :(得分:0)

你可以使用C printf(),它就像NSLog一样工作,但是不打印实际的日志信息(时间和其他信息),也不会自动添加新行(你仍然可以使用{ {1}})