Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- typedef struct s_pos
- {
- int x;
- int y;
- } s_pos;
- int main()
- {
- #define board_size 8
- int snake_count = 0;
- int apple_count = 0;
- s_pos snake[board_size * board_size] = {};
- s_pos apples[board_size * board_size] = {};
- snake[snake_count].x = 4;
- snake[snake_count].y = 4;
- snake_count += 1;
- // apples[apple_count].x = rand() % board_size;
- // apples[apple_count].y = rand() % board_size;
- apples[apple_count].x = 6;
- apples[apple_count].y = 4;
- apple_count += 1;
- while(1) {
- // Display board
- for(int y = 0; y < board_size; y++) {
- for(int x = 0; x < board_size; x++) {
- int found_apple = 0;
- int found_snake = 0;
- for(int apple_i = 0; apple_i < apple_count; apple_i++) {
- if(apples[apple_i].x == x && apples[apple_i].y == y) {
- printf("9");
- found_apple = 1;
- break;
- }
- }
- if(found_apple) { continue; }
- for(int snake_i = 0; snake_i < snake_count; snake_i++) {
- if(snake[snake_i].x == x && snake[snake_i].y == y) {
- printf("1");
- found_snake = 1;
- break;
- }
- }
- if(found_snake) { continue; }
- printf("0");
- }
- printf("\n");
- }
- // Get input
- char buffer[128] = {};
- scanf(" %c", buffer);
- char c = buffer[0];
- s_pos head = snake[0];
- // Move head
- if(c == '8') {
- head.y -= 1;
- if(head.y < 0) { head.y = board_size - 1; }
- }
- else if(c == '2') {
- head.y += 1;
- if(head.y >= board_size) { head.y = 0; }
- }
- else if(c == '4') {
- head.x -= 1;
- if(head.x < 0) { head.x = board_size - 1; }
- }
- else if(c == '6') {
- head.x += 1;
- if(head.x >= board_size) { head.x = 0; }
- }
- // Eat apple
- for(int apple_i = 0; apple_i < apple_count; apple_i++) {
- s_pos apple = apples[apple_i];
- if(head.x == apple.x && head.y == apple.y) {
- apples[apple_i] = apples[apple_count - 1];
- apple_i -= 1;
- apple_count -= 1;
- snake_count += 1;
- }
- }
- // Make snake body follow head
- for(int snake_i = snake_count - 1; snake_i >= 1; snake_i--) {
- snake[snake_i] = snake[snake_i - 1];
- }
- snake[0] = head;
- // snake[0] = head;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement