0

我的任务不需要我制作一个完整的井字游戏程序。我只需要能够将 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 打印到板上。

如何将input包含“X”或“O”的内容放置在正确的位置?我相信这些陈述应该在下面if ( selectRows == 1 && selectColumns == 1 )

如果我能做if ( selectRows == 1 && selectColumns == 1 )对,我应该能够为其他selectRowsand做对selectColumns

4

1 回答 1

1

正如 sraok 所提到的,不可能改变它打印的输出。您必须在每次输入后重新绘制您的电路板。

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

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

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

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

请记住,数组从 0 开始。如果用户想将他的 X 放在左上角,他会键入 1 1,但 'X' 必须放在 `board[0][0]' 等等。

于 2013-10-22T19:21:14.517 回答