0

我正在用c做一个井字游戏,下面代码中的wincheck函数不起作用,如果有胜利,游戏不会停止,它一直在运行,似乎wincheck函数没有使wincheckvalue 1 ,但为什么?

#include <stdio.h>
#include <stdbool.h>
char list[10] = {'0',' ',' ',' ',' ',' ',' ',' ',' ',' '};

void displayboard()
{
    printf("\n      |      |    ");
    printf("\n  %c   |  %c   |  %c ",list[7],list[8],list[9]);
    printf("\n      |      |    \n");
    printf("--------------------\n");
    printf("\n      |      |    ");
    printf("\n  %c   |  %c   |  %c ",list[4],list[5],list[6]);
    printf("\n      |      |    \n");
    printf("--------------------\n");
    printf("\n      |      |    ");
    printf("\n  %c   |  %c   |  %c ",list[1],list[2],list[3]);
    printf("\n      |      |    \n");
}

int wincheck(char c)
{
    int returnvalue = 0;
    if (list[1] == list[2] == c && list[2] == list[3] == c)
    {
        returnvalue = 1;
    }
    else if (list[4] == list[5] == c && list[5] == list[6] == c)
        returnvalue = 1;

    else if (list[7] == list[8] == c && list[8] == list[9] == c)
        returnvalue = 1;

    else if (list[1] == list[4] == c && list[4] == list[7] == c)
        returnvalue = 1;

    else if (list[2] == list[5] == c && list[5] == list[8] == c)
        returnvalue = 1;

    else if (list[3] == list[6] == c && list[6] == list[9] == c)
        returnvalue = 1;

    else if (list[1] == list[5] == c && list[5] == list[9] == c)
        returnvalue = 1;

    else if (list[3] == list[5] == c && list[5] == list[7] == c)
        returnvalue = 1;
    return returnvalue;

}


int main()
{
    int wincheckvalue;
    int v = 0;
    int a;
    int b;
    while (true)
    {       
        displayboard();
        printf("Player 1(X) ,Input num: ");
        scanf("%i",&a);
        while (list[a] == '0' || list[a] == 'X' )
        {
            displayboard();
            printf("Invalid move!\n");
            printf("Input num: ");
            scanf("%i",&a);
        }
        list[a] = 'X';
        wincheckvalue = wincheck('X');
        if (wincheckvalue == 1)
        {
            printf("Player 1 has won!!");
            break;
        }
        displayboard();
        printf("Player 2(0) ,Input num: ");
        scanf("%i",&b);
        while (list[b] == 'X' || list[b] == '0')
        {
            displayboard();
            printf("Invalid move!\n");
            printf("Input num: ");
            scanf("%i",&b);
        }
        list[b] = '0';
        displayboard();
        wincheckvalue = wincheck('0');
        if (wincheckvalue == 1)
        {
            printf("Player 2 has won!!");
            break;
        }

    }


}
4

1 回答 1

4

你所有的比较list[1] == list[2] == c都是错误的。

该比较等于(list[1] == list[2]) == c,这意味着您将 的真/假(整数10分别)结果list[1] == list[2]与 的值进行比较c。这很可能永远不会是真的。

您必须像list[1] == c && list[2] == c等一样拆分比较。

于 2021-04-13T07:39:46.147 回答