浪费几个小时搓的贪吃蛇

· · 闲话

使用了 raylib 库。

#include "bits/stdc++.h"
#include "raylib.h"
using namespace std;
const int K = 600, G = 300;
struct mvct2 {
    int x, y;
};
vector <mvct2> snk;
int f = 1, zf = 1, dx[] = {0, 0, -1, 1}, dy[] = {-1, 1, 0, 0};
bool a[25][15];
double tme;
mvct2 ap = {-1, -1};
void initd () {
    ClearBackground (WHITE);
    for (int i = 30; i < G; i += 30) {
        DrawLine (0, i, K, i, LIGHTGRAY);
    }
    for (int i = 30; i < K; i += 30) {
        DrawLine (i, 0, i, G, LIGHTGRAY);
    }
}
mvct2 qsj () {
    vector <mvct2> tmp;
    for (int i = 0; i < K / 30; i++) {
        for (int j = 0; j < G / 30; j++) {
            if (!a[i][j]) {
                tmp.push_back ({i * 30, j * 30});
            }
        }
    }
    return tmp[rand () % tmp.size ()];
}
void mdr () {
    BeginDrawing ();
    initd ();
    DrawText (TextFormat ("Score:%d", snk.size ()), 0, 0, 30, BLUE);
    DrawRectangle (ap.x, ap.y, 30, 30, RED);
    for (int i = 0; i < snk.size (); i++) {
        Color c = (i ? YELLOW : GREEN);
        DrawRectangle (snk[i].x, snk[i].y, 30, 30, c);
    }
}
void over () {
    while (!WindowShouldClose ()) {
        mdr ();
        string s = "Game Over!";
        int l = MeasureText (s.data (), 100);
        DrawText (s.data (), (K - l) >> 1, (G - 100) >> 1, 100, BLUE);
        EndDrawing ();
    }
    exit (0);
}
void move () {
    zf = f;
    mvct2 p = snk[0];
    p.x = int (p.x + dx[zf] * 30 + K) % K;
    p.y = int (p.y + dy[zf] * 30 + G) % G;
    if (p.x == ap.x && p.y == ap.y) {
        ap.x = -1;
    }
    else {
        a[snk.back ().x / 30][snk.back ().y / 30] = 0;
        snk.pop_back ();
        if (a[p.x / 30][p.y / 30]) {
            over ();
        }
    }
    snk.insert (snk.begin (), p);
    a[p.x / 30][p.y / 30] = 1;
}
void dtct () {
    if (zf != 1 && (IsKeyDown (KEY_UP) || IsKeyDown (KEY_W) || IsKeyDown (KEY_K))) 
        f = 0;
    if (zf != 0 && (IsKeyDown (KEY_DOWN) || IsKeyDown (KEY_S) || IsKeyDown (KEY_J))) 
        f = 1;
    if (zf != 3 && (IsKeyDown (KEY_LEFT) || IsKeyDown (KEY_A) || IsKeyDown (KEY_H))) 
        f = 2;
    if (zf != 2 && (IsKeyDown (KEY_RIGHT) || IsKeyDown (KEY_D) || IsKeyDown (KEY_L))) 
        f = 3;
}
int main () {
    SetTargetFPS (60);
    srand (time (0));
    InitWindow (K, G, "请输入文本");
    snk.push_back ({270, 120});
    a[9][4] = 1;
    while (!WindowShouldClose ()) {
        tme += GetFrameTime ();
        if (ap.x == -1) {
            ap = qsj ();
            a[ap.x / 30][ap.y / 30] = 1;
        }
        dtct (); 
        mdr ();
        EndDrawing ();
        if (tme < 0.1) {
            continue;
        }
        tme = 0;
        move ();
    }
    return 0;
}