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.
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.
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:
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; }
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:
The full code for the C Battlesnake can be found here on GitHub.
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中文網其他相關文章!