1

我对 C++ 非常陌生,并决定开始使用 RayLib 作为图形引擎制作 tic tac toe。下面的代码设置一个屏幕,绘制网格并检查输入。我正在处理的部分是在单击的字段中显示 X 或 O。我终于得到了绘制文本的程序,但它似乎绘制了整个数组而不是一个字母。

#include "raylib.h"
#include <string.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
    //INITIALIZE//
    int screenWidth = 750;
    int screenHeight = 750;
    char matrix[9] = {'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'};
    char currentPlayer = 'X';
    InitWindow(screenWidth, screenHeight, "raylib [core] example - basic window");
    SetTargetFPS(60);
    
    while (!WindowShouldClose())
    {   
        //INPUT//
        if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) {
            int mouseX = GetMouseX();
            int mouseY = GetMouseY();
            double x = floor(mouseX/250);
            double y = floor(mouseY/250);
            int index = x + 3*y;
            matrix[index] = currentPlayer;
            currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
        }
        //DRAWING//
        BeginDrawing();
        ClearBackground(WHITE);
        for (int i = 1; i < 3; i++) {
            int num = i*250;
            DrawLine(num, 0, num, screenWidth, LIGHTGRAY);
            DrawLine(0, num, screenHeight, num, LIGHTGRAY);
        }
        //Code I was working on
        for (int i = 0; i < 9; i++) {
            if (matrix[i] != 'E') {
                int textX = 115 + i*250 - (i%3)*750;
                int textY = 115 + (i%3)*250;
                char text = matrix[i];
                DrawText(&text, textX, textY, 20, LIGHTGRAY); //The problem is here
            }
        }
        EndDrawing();
    }
    CloseWindow();
    return 0;
}

当我单击左上角的单元格以绘制 X 时,它会改为绘制“XXEEEEEEEE0?D”。有谁知道如何从数组中只绘制一个字符?

提前致谢!

4

3 回答 3

3

C 风格的字符串以空字符 ( \0) 终止,因此您必须添加它,否则您必须让它越界读取并调用未定义行为

所以,

char text = matrix[i];

应该

char text[] = {matrix[i], '\0'};

DrawText(&text, textX, textY, 20, LIGHTGRAY);

应该

DrawText(text, textX, textY, 20, LIGHTGRAY);

&(之前删除text

于 2020-08-17T18:14:50.827 回答
3

DrawText()需要一个以空字符结尾的字符串作为输入,但你给它一个单一的char。改变这个:

char text = matrix[i];
DrawText(&text, ...);

对此:

char text[2] = {matrix[i], '\0'};
DrawText(text, ...);
于 2020-08-17T18:15:03.347 回答
0

你可以这样做:

            char text = matrix[i];
            char shortenedText[2] = {0, 0};
            shortenedText[0] = text;
            DrawText(shortenedText, textX, textY, 20, LIGHTGRAY); //The problem is here

基本上用一个字符构建一个非常小的字符串。

于 2020-08-17T18:15:42.417 回答