Крестики-нолики в C (с использованием двумерного массива символов) - PullRequest
0 голосов
/ 13 февраля 2019

Я просмотрел различные другие посты, рассматривая, как реализовать Tic-Tac-Toe в C, но, к сожалению, сталкиваюсь с проблемами.У меня есть две функции для инициализации и рисования сетки, int init_grid(int gridsize) и void draw_grid(int gridsize).Они принимают параметр gridsize, поскольку пользователь может выбирать сетку от 3х3 до 10х10.Программа до сих пор компилируется, но при вводе размера доски она печатает правильное число '.'символов, но только в первом столбце.

Код выглядит следующим образом:

init_grid

int init_grid(int gridsize) {


for (int row = 0; row < gridsize ; row++) {

    for (int col = 0; col < gridsize; col++) {
        grid[row][col] = '.';
    }
}

if (gridsize > MaxGrid) {
    puts("Error, gridsize too large.");
    return 1;
}

else {
    return 0;
  }
}

draw_grid

void draw_grid(int gridsize) {

for (int row = 0; row < gridsize; row++)
{
    for (int col = 0; row < gridsize; row++)
    {   
        putchar (' ');
        if (grid[row][col]) {
            putchar (grid[row][col]);
        }
        else {
            putchar ('.');
        }

    printf("\n");
   }
  }
 }

основной

int main() {

int gridsize = 0;

printf("Hello and welcome to Tic Tac Toe\n");
printf("Please enter the size of the grid you would like to play with (between 3 and 10):\n");
scanf("%d", &gridsize);

init_grid(gridsize);
draw_grid(gridsize);

return 0;
}

Выход

Hello and welcome to Tic Tac Toe
Please enter the size of the grid you would like to play with (between 3 and 
10):
 5
 .
 .
 .
 .
 .

Desired output

Iнадеюсь, я все прояснил.Сейчас я пробовал разные вещи, но просто не могу заставить его правильно печатать доску / сетку.

1 Ответ

0 голосов
/ 13 февраля 2019

Все комментарии выше верны.Я поместил весь исправленный код ниже, и теперь код работает как ожидалось.

Я также добавил код для обозначения строк и столбцов.Обратите внимание, что изменения должны быть сделаны, когда размер сетки больше 9.

#include <stdio.h>

int init_grid(int gridsize);
void draw_grid(int gridsize);

char grid[25][25];
int MaxGrid = 25;


int init_grid(int gridsize)
{
    for (int row = 0; row < gridsize ; row++)
    {
        for (int col = 0; col < gridsize; col++)
        {
            grid[row][col] = '.';
        }
    }

    if (gridsize > MaxGrid)
    {
        puts("Error, gridsize too large.");
        return 1;
    }
    else
    {
        return 0;
    }
}


void draw_grid(int gridsize)
{

    printf("    ");
    for( int i=0; i < gridsize; i++ )
    {
        printf("%d ", i+1);
    }
    printf("\n");

    for (int row = 0; row < gridsize; row++)
    {
        printf("%d  ", row+1);
        for (int col = 0; col < gridsize; col++)
        {   
            putchar (' ');
            if (grid[row][col])
            {
                putchar (grid[row][col]);
            }
            else
            {
                putchar ('.');
            }
        }
        printf("\n");
    }
}


int main()
{

    int gridsize = 0;

    printf("Hello and welcome to Tic Tac Toe\n");
    printf("Please enter the size of the grid you would like to play with (between 3 and 10):\n");
    scanf("%d", &gridsize);

    init_grid(gridsize);
    draw_grid(gridsize);

    return 0;
}

Вывод:

jnorton@ubuntu:~/source$ ./a.out 
Hello and welcome to Tic Tac Toe
Please enter the size of the grid you would like to play with (between 3 and 10):
5
    1 2 3 4 5 
1   . . . . .
2   . . . . .
3   . . . . .
4   . . . . .
5   . . . . .
jnorton@ubuntu:~/source$ ./a.out 
Hello and welcome to Tic Tac Toe
Please enter the size of the grid you would like to play with (between 3 and 10):
3
    1 2 3 
1   . . .
2   . . .
3   . . .
jnorton@ubuntu:~/source$ ./a.out 
Hello and welcome to Tic Tac Toe
Please enter the size of the grid you would like to play with (between 3 and 10):
10
    1 2 3 4 5 6 7 8 9 10 
1   . . . . . . . . . .
2   . . . . . . . . . .
3   . . . . . . . . . .
4   . . . . . . . . . .
5   . . . . . . . . . .
6   . . . . . . . . . .
7   . . . . . . . . . .
8   . . . . . . . . . .
9   . . . . . . . . . .
10   . . . . . . . . . .
jnorton@ubuntu:~/source$ 
...