> 백엔드 개발 > C++ > 본문

배틀스네이크 챌린지 #C

王林
풀어 주다: 2024-07-16 16:45:58
원래의
628명이 탐색했습니다.

In this series I'll share my progress with my self-imposed programming challenge: build a Battlesnake in as many different programming languages as possible.

Check the first post for a short intro to this series.

You can also follow my progress on GitHub.

C

After Python and JavaScript, it's time to roll up the sleeves and pick a language that requires a bit more serious development effort: C.

C is the language of Operating Systems and embedded software. The language has only basic data types, and its standard library offers no convenient high-level functionalities such as JSON parsers or web servers.
To make things even more challenging: in C memory management is the responsibility of the developer, not the language. It has been a while since I needed to do that.

All-in-all, not a great match for building a Battlesnake, but I guess not all implementations can be done within 100 lines of code.

Hello world Setup

This is how snake.c looks:

#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("Hello world!\n");
}
로그인 후 복사

This is how the Dockerfile looks:

FROM gcc:14
RUN mkdir /app
WORKDIR /app
COPY snake.c .
RUN gcc -o snake snake.c
CMD ["./snake"]
로그인 후 복사

And here's the development setup in action:

A basic web server

There's no simple web server available in the standard C library.
Writing a web server from scratch, even a simple one, is a huge amount of work and code.
Fortunately, because there are only 4 API endpoints that need to be implemented, and the input is known beforehand, I could cut a lot of corners.
The main connection handling loop looks like this:

while (1) {
    int client_socket = accept(server_socket, &client_address,
        &client_address_len);
    int buffer_size = 32768;
    char *buffer = (char *)malloc(buffer_size * sizeof(char));
    int bytes = (int)recv(client_socket, buffer, buffer_size, 0);
    const char *get_meta_data = "GET /";
    const char *post_start = "POST /start";
    const char *post_move = "POST /move";
    const char *post_end = "POST /end";
    if (strncmp(buffer, get_meta_data, strlen(get_meta_data)) == 0) {
        handle_get_meta_data(client_socket);
    } else if (strncmp(buffer, post_start, strlen(post_start)) == 0) {
        char *body = get_body(client_socket, buffer, buffer_size, bytes);
        handle_start(client_socket, body);
    } else if (strncmp(buffer, post_move, strlen(post_move)) == 0) {
        char *body = get_body(client_socket, buffer, buffer_size, bytes);
        handle_move(client_socket, body);
    } else if (strncmp(buffer, post_end, strlen(post_end)) == 0) {
        handle_end(client_socket);
    }
    close(client_socket);
    free(buffer);
}
로그인 후 복사

A thing that gave me a real headache was handling the HTTP body properly, as the HTTP request can be received chunked in smaller parts:

char *get_body(int client_socket, char *buffer, int buffer_size, int bytes) {
    int content_length = get_content_length(buffer);
    char *result = strstr(buffer, "\r\n\r\n") + 4;
    while (strlen(result) < content_length) {
        char *ptr = buffer + bytes;
        bytes += (int)recv(client_socket, ptr, buffer_size - bytes, 0);
        result = strstr(buffer, "\r\n\r\n") + 4;
    }
    return result;
}
로그인 후 복사

Game logic

A big part of the game logic code is there to parse the incoming JSON data. The standard C library does not contain a JSON parser, and a typical parser library contains thousands of lines of code. With a lot of hacks I was able to parse the Battlesnake JSON, and only that JSON, in less than 50 lines of code.

Below are two of the five functions in the code related to JSON parsing:

char * get_field(const char *json, const char *name) {
    char *needle = (char *)malloc((strlen(name) + 3) * sizeof(char));
    sprintf(needle, "\"%s\"", name);
    char *ptr = strstr(json, needle);
    ptr += strlen(needle) + 1;
    free(needle);
    return ptr;
}

char * get_object(const char *json, const char *name, char *buffer) {
    char *ptr = get_field(json, name);
    int idx = 0, indent = 0;
    do {
        if (*ptr == '{')
            indent++;
        else if (*ptr == '}')
            indent--;
        buffer[idx++] = *ptr++;
    } while (indent > 0);
    buffer[idx] = '\0';
    return buffer;
}
로그인 후 복사

The remainder of the game logic is quite mundane, and very simplistic:

void preferred_directions(char *board, int head_x, int head_y, int dirs[]) {
    char *buffer = (char *)malloc(strlen(board) * sizeof(char));
    char *food = get_array(board, "food", buffer);
    int food_x = 256;
    int food_y = 256;
    nearest_food(food, head_x, head_y, &food_x, &food_y);
    if (head_x != food_x) {
        if (head_x < food_x) {
            dirs[0] = RIGHT;
            dirs[3] = LEFT;
        } else {
            dirs[0] = LEFT;
            dirs[3] = RIGHT;
        }
        dirs[1] = UP;
        dirs[2] = DOWN;
    } else {
        if (head_y < food_y) {
            dirs[0] = UP;
            dirs[3] = DOWN;
        } else {
            dirs[0] = DOWN;
            dirs[3] = UP;
        }
        dirs[1] = LEFT;
        dirs[2] = RIGHT;
    }
    free(buffer);
}
로그인 후 복사

I'm sure it can be improved a lot by anyone who spend a bit more time on it. But for my challenge this is fine, although admittedly the C snake is not the sharpest tool in the shed.

And this is the complete code in action:

C Battlesnake

The full code for the C Battlesnake can be found here on GitHub.

Feedback appreciated!

I hope you like reading along with my coding adventures.

Let me know in the comments below what you think about the code above, or what programming languages you are looking forward to in this series.

Until the next language!

위 내용은 배틀스네이크 챌린지 #C의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!