c - 在由数组、循环和 if 语句组成的简单 Tic-Tac-Toe 游戏中打印标记为 'X' 'O'

标签 c arrays loops if-statement nested-loops

我的任务不需要我制作一个完整的井字游戏程序。我只需要能够将 X 和 O 打印到板上。

此时我需要将“X”和“O”打印到板上,这是最后一个阶段。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    //Declare the variables
    //Create the board
        //Initialize the board with all blanks
        //Print to screen
    //Prompt user for letter 'X', 'O' or 'q' to quit
        //if the input is q, then quit.
        //if the input is X or O then select positions.
            //prompt user to choose rows & columns to mark X O positions

    //declare the variables
    char board[3][4], input; //input is for the X O q
    char selectRows, selectColumns; //these are for choosing position to mark X or O
    int rows, columns;

    //create the basic empty board
    for ( rows = 0 ; rows <3 ; rows++ )
    {
        for ( columns = 0 ; columns < 4 ; columns++ )
        {
            //Initialize array to blanks (' ')
            board[rows][columns] = '|';

            //print to screen
            printf( "%c   ", board[rows][columns] );
        }
        printf("\n\n\n");
    }

    //prompt the user to input X or O
    printf( "\nHit X or O. 'q' to quit\n" );
    scanf("%c", &input);

    while ( input != 'q' )
    {
        //if the input is 'X' or 'O'
        if ( input == 'X' || input == 'O' )
        {
            //select rows
            printf("Choose 1 - 3 For Rows ");
            scanf( "\n%c", &selectRows );

            //select columns
            printf("Choose 1 - 3 For Columns ");
            scanf( "\n%c", &selectColumns );

            //Print X or O on the board
            if ( selectRows == 1 && selectColumns == 1 )

                //prompt user to hit in X or O, q to quit again
                printf( "\nHit X or O. 'q' to quit\n" );

            scanf("%c", &input);
        }

    } //end while
}//end main

因此我能够打印空板并请求用户输入 X 或 O 或 q 来退出游戏。

但是我不知道如何将 X 和 O 打印到板上。

如何将包含“X”或“O”的输入放置在正确的位置?我相信这些语句应该位于 if ( selectRows == 1 && selectColumns == 1 )

下面

如果我能得到 if ( selectRows == 1 && selectColumns == 1 ) 正确,我应该能够为其他 selectRows 得到正确的结果选择列

最佳答案

正如 sraok 所提到的,不可能更改打印的输出。每次输入后您都必须重新绘制棋盘。

因此,我建议您定义一个函数(例如 drawBoard),该函数将 2d 字符数组作为输入,例如称为 board[][]。该数组用空格 "" 初始化。 这意味着您的 | 之间的所有字段默认为空。

如果用户想放置X,可以设置对应的数组元素

board[selectRows][selectColumns] = 'X';

用“X”覆盖此位置的“”,并将更新后的 board 数组传递给重绘板的 drawBoard 函数。

请记住,数组从 0 开始。如果用户想要将 X 放在左上角,他可以输入 1 1,但是“X”必须放在“board[0][0]”处,并且等等。

关于c - 在由数组、循环和 if 语句组成的简单 Tic-Tac-Toe 游戏中打印标记为 'X' 'O',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19524134/

相关文章:

c - 理解为什么 execvp 在 `execv` 失败的地方起作用

arrays - 如何在 MongoDB 中同时查询两个数组?

arrays - 如何索引汇编中的字符串

java - 在二维数组的边界周围制作一个星形的正方形

java - 从某个点循环播放声音文件?

基于 PHP 值的 PHP 循环

c - 在像 a[0-15] 这样的数组中,如何检查是否有任何数组相同,如果相同则合并它们的总数?

c - 了解 boolean 值上的 "not"

arrays - 来自 Yaml 的数组 - Golang

c++ - 从注册表项中提取多个 IClass 值