所以,我正在尝试用 raylib 用 C 语言制作一个简单的蛇游戏,在添加了吃苹果的能力之后,基本上一切都崩溃了。我这样做的方式是,有一个 Vector2 数组,它给出了蛇的每个正方形的位置,它被渲染为 20x20 网格。这是代码,这有点像意大利面条,因为我是一个糟糕的程序员,但我希望有人能帮助我。
#include <stdlib.h>
#include <time.h>
#include <raylib.h>
#define WIDTH 1080
#define HEIGHT 1080
#define FPS 4
#define GRIDSIZE 20
int main()
{
// Random Numbers
srand(time(NULL));
// Define locations
Vector2 playerLoc[10] = {(Vector2) {rand() % GRIDSIZE, rand() % GRIDSIZE}};
Vector2 appleLoc = (Vector2) {rand() % GRIDSIZE, rand() % GRIDSIZE};
// Player Score
int score = 0;
// Define Direction
Vector2 playerDir = (Vector2) {1, 0};
// With of Grid Squares
int gridSize = HEIGHT / GRIDSIZE;
// Initialization
InitWindow(WIDTH, HEIGHT, "Snake Game Test");
SetTargetFPS(FPS);
while (!WindowShouldClose())
{
// Update Variables Here
if (IsKeyPressed('D') || IsKeyPressed('A'))
{
playerDir.x = (int) IsKeyPressed('D') - (int) IsKeyPressed('A');
playerDir.y = 0.0f;
}
else if (IsKeyPressed('S') || IsKeyPressed('W'))
{
playerDir.y = (int) IsKeyPressed('S') - (int) IsKeyPressed('W');
playerDir.x = 0;
}
for (int i = 0; i <= score; i++)
{
playerLoc[i].x += playerDir.x;
playerLoc[i].y += playerDir.y;
}
if (playerLoc[0].x < 0)
break;
else if (playerLoc[0].x >= 1080)
break;
else if (playerLoc[0].y < 0)
break;
else if (playerLoc[0].y >= 1080)
break;
if (playerLoc[0].x == appleLoc.x && playerLoc[0].y == appleLoc.y)
{
appleLoc = (Vector2) {rand() % GRIDSIZE, rand() % GRIDSIZE};
score++;
playerLoc[score].x = playerLoc[score - 1].x + (playerDir.x * -1);
playerLoc[score].y = playerLoc[score - 1].y + (playerDir.y * -1);
}
// Draw
BeginDrawing();
ClearBackground(RAYWHITE);
for (int i = 0; i < GRIDSIZE; i++)
{
for (int j = 0; j < GRIDSIZE; j++)
{
for (int k = 0; k <= score; k++)
{
if (i == playerLoc[k].x && j == playerLoc[k].y)
DrawRectangle(i * gridSize, j * gridSize, gridSize, gridSize, BLACK);
}
if (i == appleLoc.x && j == appleLoc.y)
{
DrawRectangle(i * gridSize, j * gridSize, gridSize, gridSize, RED);
}
}
}
EndDrawing();
// Update Late Variables Here
}
// De-Initialization
CloseWindow();
return 0;
}