我正在学习 C,并制作了一个井字游戏桌。现在,我如何引用各个单元格?

发布于 2024-09-13 13:58:07 字数 1463 浏览 1 评论 0原文

我正在学习 C,所以决定尝试制作一个 Tic Tac Toe 游戏,使用 ASCII 艺术作为表格。

我还没有太多...

#include <stdio.h> 

#define WIDTH 2;

#define HEIGHT 2;

int main (int argc, char *argv[]) {

    printf("Welcome to Tic Tac Toe!\n\n");

    int width = WIDTH;
    int height = HEIGHT;

    // Make grid

    for (int y = 0; y <= height; y++) {

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

            printf("%d%d", x, y);

            if (x != width) {
                printf("||");
            }

        }


        if (y != height) {
            printf("\n");

            for (int i = 0; i < (width + (width * 4)); i++) {
                printf("=");
            }

            printf("\n");
        } else {
            printf("\n");
        }


    }

    // Ask for user input

    printf("Please enter the cell where you would like to place an X, e.g. for example the first top left cell is '00'\n");

}

当在命令行上运行时,我得到了这个输出

Welcome to Tic Tac Toe!

00||10||20
==========
01||11||21
==========
02||12||22
Please enter the cell where you would like to place an X, e.g. for example the first top left cell is '00'

现在,当我弄清楚如何获取多个字符的输入时(我只知道如何使用 getchar()< /code> 到目前为止获取单个字符,尽管对于本示例来说这可能工作正常),我想再次循环并为相应的单元格放置一个 X。

我是否应该编写一个用于打印表格的函数,该函数采用“intmarkerX,intmarkerY”等参数来放置X?

然后我将如何存储标记的位置,以便我可以检查游戏是否获胜?

我的选择要放置标记的单元格是在命令行上请求用户输入游戏的最佳方式吗?

谢谢!

I'm learning C, so decided to try and make a Tic Tac Toe game, using ASCII art as the table.

I don't have much yet...

#include <stdio.h> 

#define WIDTH 2;

#define HEIGHT 2;

int main (int argc, char *argv[]) {

    printf("Welcome to Tic Tac Toe!\n\n");

    int width = WIDTH;
    int height = HEIGHT;

    // Make grid

    for (int y = 0; y <= height; y++) {

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

            printf("%d%d", x, y);

            if (x != width) {
                printf("||");
            }

        }


        if (y != height) {
            printf("\n");

            for (int i = 0; i < (width + (width * 4)); i++) {
                printf("=");
            }

            printf("\n");
        } else {
            printf("\n");
        }


    }

    // Ask for user input

    printf("Please enter the cell where you would like to place an X, e.g. for example the first top left cell is '00'\n");

}

When ran on the command line, I get this output

Welcome to Tic Tac Toe!

00||10||20
==========
01||11||21
==========
02||12||22
Please enter the cell where you would like to place an X, e.g. for example the first top left cell is '00'

Now, when I figure out how to get input of more than one char (I only know how to use getchar() for getting individual chars so far, though that might work OK for this example), I'd like to loop through again and place an X for the corresponding cell.

Should I write a function for printing the table, which takes arguments such as 'int markerX, int markerY` to place the X?

How would I then store the position of the marker so I could check if the game is won or not?

Is my Choose which cell to place marker the best way to ask for user input for a game on the command line?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

ぃ双果 2024-09-20 13:58:08

您当前无法引用这些单元格,因为您没有将这些值存储在任何地方。您需要创建一个变量来存储单元格中的值。要修改单元格的值,您需要做的就是更改关联变量的值并重新绘制表格。

为了使事情变得更简单,您可以编写一个 draw_table 函数,使用变量的当前值绘制井字游戏板。

如果您仅使用 getch 进行输入,那么您可以将单元格称为 1-9,而不是使用两位数。这也可能使跟踪变量变得更容易,您可以将它们称为 cell1cell2 等。您也可以使用数组,但这可能太复杂如果你刚刚开始。

You can't currently reference the cells because you don't store the values anywhere. You need to create a variable to store the value in a cell. To modify the value of a cell all you would need to do is change the value of the associated variable and re-draw the table.

To make things easier, you might write a draw_table function that draws the tic-tac-toe board using the current value of your variables.

If you are only using getch for input, then you might refer to your cells as 1-9 instead of using a two-digit number. This might also make it easier to keep track of your variables, you can call them cell1, cell2, etc. You can also use an array, but that might be too complicated if you are just starting out.

远昼 2024-09-20 13:58:07

现在,您已经很好地弄清楚了如何将井字游戏板输出到屏幕上,但您当前缺少的是内存中井字游戏板的模型您的程序可以修改并使用它来重新打印电路板的当前状态。

通常,每当您需要对二维元素网格进行建模时,表示这些元素的最简单模型就是二维数组。您可以这样定义一个:

int board[WIDTH][HEIGHT]

然后您可以通过索引引用它来访问板上任何元素的当前状态(索引总是从 0 到 1 小于数组中的元素数量,如下所示

int element = board[0][1]

:将板输出给用户时,您可能需要实现一个打印板的函数,包括其当前状态。一旦该函数存在,您就可以随时在代码中调用该函数,而无需重复自己

while 是最适合这种情况的结构 - 它会循环直到条件为真。

int shouldExit = 0;
while (shouldExit == 0) {
    printBoard();
    getPlayerInput();
    updateBoard();

    // you can set shouldExit to 1 if the game is over 
    // (someone won, or the player inputted something that indicates they want to quit.
}

Right now you've done a pretty good job of figuring out how to output a tic-tac toe board to the screen, but what you are currently lacking is a model of your tic-tac board in memory that your program can modify and use to reprint the current status of the board.

Typically, whenever you have a 2 dimensional grid of elements to model, the simplest model to represent these is a 2-dimensional array. You can define one like this:

int board[WIDTH][HEIGHT]

Then you can access the current state of any element on the board by referencing it by it's index (which always goes from 0-1 less than the number of elements in the array, like so:

int element = board[0][1]

To re-output the board to the user, you may want to implement a function that prints out the board, including its current state. Once that function exists, you can always call that in your code without needing to repeat yourself.

Finally, you'll need to implement a loop. while is the structure most suited to this - it loops until a condition is true.

int shouldExit = 0;
while (shouldExit == 0) {
    printBoard();
    getPlayerInput();
    updateBoard();

    // you can set shouldExit to 1 if the game is over 
    // (someone won, or the player inputted something that indicates they want to quit.
}
安静被遗忘 2024-09-20 13:58:07

我将创建一个函数,其唯一的工作是打印板,如下所示(未经测试):

void board_print(const char b[3][3]) }
   int i = 1;
   printf(        "     A   B   C\n");     // NOTE: Letters on top, like a spreadsheet
   while (1) {
      printf(      "%i  %c | %c | %c\n", i, b[i][0], b[i][1], b[i][2]);
      if (++i <=3) {
          printf(  "  ---+---+---\n");
      } else {
         break;
      }
   }
}

然后创建一个如下板:

int main(void) {
    char board[3][3] =
        {{ ' ', ' ', ' ' },
         { ' ', ' ', ' ' },
         { ' ', ' ', ' ' }};

    while (1) {
       board_print(board);
       printf("Place X at : ");

然后我将创建另一个函数,其整个工作是尝试将 X 或 O 放置在某个位置:

int board_place(char board[3][3], 字符标记, 字符行, 字符列);

这里的marker可以是“x”或“o”。

board_place 可以返回一个值,您可以使用该值来确定游戏的总体状态。例如,如果 board_place 无法移动,因为该位置已经有一个标记,那么如果该行超出范围,它应该返回一个不同的错误代码。这也可以是您确定是否有获胜者的地方(因为当前的举动将是获胜的举动{简单,因为您只需测试包括当前方块的线})或者棋盘是否已满且没有获胜者并返回其中每一个都有不同的东西。

然后你的主代码就根据board_place的返回值来决定做什么(向用户发出错误信息并提示换一个位置,尝试为O走一步,恭喜用户胜利,告诉用户猫赢得了那一场,...)。

就阅读位置而言,这就是用户界面与文本处理的结合。一个简单的 scanf 调用就足够了,或者可能只是几个 getchar 调用。我确实建议您以不同的方式对行和列进行索引(我使用字母和数字),因为这对大多数人来说可能会更容易。然后,您可以在 board_place 之前进行调整,也可以只调整 board_place 中的索引。

I would create a function whose only job was to print the board, like this (untested):

void board_print(const char b[3][3]) }
   int i = 1;
   printf(        "     A   B   C\n");     // NOTE: Letters on top, like a spreadsheet
   while (1) {
      printf(      "%i  %c | %c | %c\n", i, b[i][0], b[i][1], b[i][2]);
      if (++i <=3) {
          printf(  "  ---+---+---\n");
      } else {
         break;
      }
   }
}

And then create a board like this:

int main(void) {
    char board[3][3] =
        {{ ' ', ' ', ' ' },
         { ' ', ' ', ' ' },
         { ' ', ' ', ' ' }};

    while (1) {
       board_print(board);
       printf("Place X at : ");

Then I would create another function whose entire job is to attempt to place an X or an O in a position:

int board_place(char board[3][3], char marker, char row, char column);

marker here would either be an 'x' or an 'o'.

board_place could return a value which you can use to determine the general state of play. For instance if board_place could not make the move because there was already a marker in that position then it should return a distinct error code from if the row was out of range. This could also be where you determine if there is a winner (because the current move would be the winning move {easy since you only have to test for lines made including the current square}) or if the board is full with no winner and return distinct things for each of these.

Then your main code just decides what to do based on the return value of board_place (issue an error message to the user and prompt for another position, try to make a move for O, congratulate the user on victory, tell the user that the cat won that one, ...).

As far as reading in the position, that's where user interface meets text processing. A simple scanf call could be enough, or maybe just a few getchar calls. I do suggest that you index the rows and columns differently (I used letters and numbers) because that would probably be easier for most people. Then you can either adjust before board_place or just handle adjusting the indexes within board_place.

夜唯美灬不弃 2024-09-20 13:58:07

将游戏状态存储在某种数据结构中可能是个好主意——我建议使用二维字符数组来存储玩家 1 或玩家 2 是否在其中放置了标记。

char board[WIDTH][HEIGHT];

然后,在初始化数组中的每个元素后,您可以访问那里是否有标记,

board[1][2]

例如,如果您想获取 1、2 处的标记。

现在,每次棋盘发生变化时,您可以编写一个打印的函数像以前一样使用嵌套的 for 循环再次从板中取出,只不过现在您将访问 2d 数组。

It's probably a good idea to store your game status in some data structure--I'd recommend a two-dimensional array of chars that store whether player 1 or player 2 has placed a marker there.

char board[WIDTH][HEIGHT];

Then after you initialize each element in the array, you can access whether or not there is a marker there with

board[1][2]

for example if you wanted to get the marker at 1, 2.

Now each time the board changes, you can write a function that prints out the board again using a nested for-loop like you did before, except now you'll be accessing the 2d array instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文