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"); } </stdio.h>
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) <h2> Game logic </h2> <p>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, <em>and only that JSON</em>, in less than 50 lines of code.</p> <p>Below are two of the five functions in the code related to JSON parsing:<br> </p> <pre class="brush:php;toolbar:false">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 <p>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.</p> <p>And this is the complete code in action:</p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172111956159191.gif?x-oss-process=image/resize,p_40" class="lazy" alt="C Battlesnake" loading="lazy" style="max-width:90%" style="max-width:90%" data-animated="true"></p> <p>The full code for the C Battlesnake can be found here on GitHub.</p> <h2> Feedback appreciated! </h2> <p>I hope you like reading along with my coding adventures.</p> <p>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.</p> <p>Until the next language!</p>
The above is the detailed content of Battlesnake Challenge # C. For more information, please follow other related articles on the PHP Chinese website!

The future development trends of C and XML are: 1) C will introduce new features such as modules, concepts and coroutines through the C 20 and C 23 standards to improve programming efficiency and security; 2) XML will continue to occupy an important position in data exchange and configuration files, but will face the challenges of JSON and YAML, and will develop in a more concise and easy-to-parse direction, such as the improvements of XMLSchema1.1 and XPath3.1.

The modern C design model uses new features of C 11 and beyond to help build more flexible and efficient software. 1) Use lambda expressions and std::function to simplify observer pattern. 2) Optimize performance through mobile semantics and perfect forwarding. 3) Intelligent pointers ensure type safety and resource management.

C The core concepts of multithreading and concurrent programming include thread creation and management, synchronization and mutual exclusion, conditional variables, thread pooling, asynchronous programming, common errors and debugging techniques, and performance optimization and best practices. 1) Create threads using the std::thread class. The example shows how to create and wait for the thread to complete. 2) Synchronize and mutual exclusion to use std::mutex and std::lock_guard to protect shared resources and avoid data competition. 3) Condition variables realize communication and synchronization between threads through std::condition_variable. 4) The thread pool example shows how to use the ThreadPool class to process tasks in parallel to improve efficiency. 5) Asynchronous programming uses std::as

C's memory management, pointers and templates are core features. 1. Memory management manually allocates and releases memory through new and deletes, and pay attention to the difference between heap and stack. 2. Pointers allow direct operation of memory addresses, and use them with caution. Smart pointers can simplify management. 3. Template implements generic programming, improves code reusability and flexibility, and needs to understand type derivation and specialization.

C is suitable for system programming and hardware interaction because it provides control capabilities close to hardware and powerful features of object-oriented programming. 1)C Through low-level features such as pointer, memory management and bit operation, efficient system-level operation can be achieved. 2) Hardware interaction is implemented through device drivers, and C can write these drivers to handle communication with hardware devices.

C is suitable for building high-performance gaming and simulation systems because it provides close to hardware control and efficient performance. 1) Memory management: Manual control reduces fragmentation and improves performance. 2) Compilation-time optimization: Inline functions and loop expansion improve running speed. 3) Low-level operations: Direct access to hardware, optimize graphics and physical computing.

The truth about file operation problems: file opening failed: insufficient permissions, wrong paths, and file occupied. Data writing failed: the buffer is full, the file is not writable, and the disk space is insufficient. Other FAQs: slow file traversal, incorrect text file encoding, and binary file reading errors.

In-depth analysis of C language file operation problems Preface file operation is an important function in C language programming. However, it can also be a challenging area, especially when dealing with complex file structures. This article will deeply analyze common problems in C language file operation and provide practical cases to clarify solutions. When opening and closing a file, there are two main modes: r (read-only) and w (write-only). To open a file, you can use the fopen() function: FILE*fp=fopen("file.txt","r"); After opening the file, it must be closed after use to free the resource: fclose(fp); Reading and writing data can make


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Mac version
God-level code editing software (SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software