C编程:如何在每个单元格中创建带有令牌的游戏板?

时间:2015-01-13 07:51:22

标签: c

我正在创建一个带有令牌的游戏板,用于练习。 它是一个我已经创建的9x9板,但是我在将每个单元中添加了令牌时遇到了问题。每当我为代币添加我的代码时,它会搞砸我游戏板的格式。 我对C很新,很抱歉,如果这可能是一个愚蠢的问题,但我已经尝试过自己搜索并修复它,但到目前为止还没有运气。任何帮助,将不胜感激。

这是我的游戏板代码:

int x,y; 

for (x=0; x<9; x++)
{ 
    printf (" +"); 
    for (y=0; y<9; y++)  
      printf("---+"); 
    printf ("\n%d", x+1); 
    printf (" |"); 
    for (y=0; y<9; y++) 
      printf(" |"); 
    printf ("\n"); 
} 
printf (" +"); 
for (y=0; y<9; y++) 
  for (y=0; y<9; y++) 
    printf("---+"); 
printf ("\n"); 

这是我显示令牌的代码:

for(x=0; x<9; x++)
{
    printf(" ");
    switch(board[y][x])
    {
        case PEG:
            printf("o");
            break;
        case HOLE:
            printf(".");
            break;
        case INVALID:
            printf(" ");
    }
}

我需要在所有单元格中显示“o”,并且“。”仅显示在中间单元格中。

这是我创建的主板:

+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |
+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |
+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |  
+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |
+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |
+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   |
+---+---+---+---+---+---+---+

2 个答案:

答案 0 :(得分:2)

您无法先打印电路板轮廓/边框,然后打印内容。你需要“交错”,这样你就不会弄乱当前的光标位置。

这样做的一种方法是迭代超过电路板的尺寸,即代替od 9x9,迭代11x11区域,并使用if检查当前位置是在板上还是在边框上

答案 1 :(得分:1)

检查以下代码:

     #include <stdio.h>
        int main(void) {
        int a[9][9];
        int i,j,k;
        for(i=0;i<9;i++) 
        printf("+---");


        printf("+\n");
        memset(a,0,sizeof(a));
        for(i=0;i<9;i++)
        {
            for(j=0;j<9;j++)
            {
              if( i == 4 && i==j )
            printf("| . ");
            else
            printf("| %d ",a[i][j]);
            }
            printf("|\n");
            for(k=0;k<9;k++) 
            printf("+---");

            printf("+\n");
        }

        return 0;
      }

输出:

+---+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | . | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+---+---+---+---+