Using C language + one-way linked list to realize a greedy snake __c language

Source: Internet
Author: User
Tags clear screen sleep function
first, the effect:


Second, the implementation of the steps: (I write code is to follow the steps of the following step-by-step implementation, incidentally, draw a picture on the paper ideas)

Third, function: 1. Press the top and bottom direction key movement 2. Press + or-accelerate or decelerate 3. Game failure when hitting the wall or biting into a snake body 4. Record the amount of food eaten, ie score
Four, the difficulty: how to realize the movement of the Snake body Set a timer (sleep function) in the while loop so that the program executes once every 0.5 seconds to make the snake move.
general idea: Snake body movement will encounter two kinds of situations: 1. The next node of the snake head is food: eat food, do not release tail node memory, regenerate food 2. The next node of the snake head is not food: in the snake head malloc memory to generate a new node, the snake tail node memory free off
My idea: the food node in the stack allocated memory, the regeneration of food is only modify the food node x/y value, and the Snake body node is dynamically allocated memory.
then the realization of the idea is: each cycle, the first node of the snake head x/y coordinates corresponding to +1, and head interpolation in the first node of the snake before allocating memory to insert a node. Compare the x/y coordinates of the first node of the snake head with the food node 1. If the next node is judged to be food, do not release the tail node memory and regenerate the food. 2. If you decide that the next node is not food, release the last node of the snake.
Insert new node diagram:

Five, the code is as follows (compilation environment: vs2017):
#define _crt_secure_no_warnings #include <stdio.h> #include <windows.h> #include <time.h> #include <stdlib.h>//Snake State, U: up; d: down; L: Left R: Right #define U 1 #define D 2 #define L 3 #define R 4 #define EMPTY 0 #define Bit_s
	ELF 1//bite to the snake body #define Touch_wall 2//hit the wall #define TRUE 1 #define FALSE 0 typedef struct SNAKE//snake body of a node {int x;
	int y;
struct SNAKE *next;

}snake;

The head is used to point to the first node of the snake, identifying the whole snake, but not the node of the snake snake Head, *temp_ptr, Food_node; Direction type Direction//game_over_reason record game failure reason//speed move speed int direction = R, Game_over_reason = EMPTY, Spee

d = 100;						void Locateandprint (int x, int y);						Output the box void locateandclear (int x, int y) at the cursor position;										Clears the box void Creatmap () at the cursor position;										Create a map void Createfood (); Create food void intsnake (int snake_len, int start_x, int start_y);											Initialization of the Snake Body Void endgame ();								End game void Getentereddirection ();										Gets the type of direction void Snakemove ();										Snake mobile void startgame (); Game Loop * * At the cursor position output box/void LocateAndprint (int x, int y) {//positioning COORD POS;
	HANDLE Houtput; Pos.
	x = x; Pos.
	y = y;
	Houtput = GetStdHandle (Std_output_handle);

	SetConsoleCursorPosition (Houtput, POS);
Output printf ("");
	/* Clear the box at the cursor position/void locateandclear (int x, int y) {//positioning COORD POS;
	HANDLE Houtput; Pos.
	x = x; Pos.
	y = y;
	Houtput = GetStdHandle (Std_output_handle);

	SetConsoleCursorPosition (Houtput, POS);

Output printf ("");}

	* * Create map/void Creatmap () {//Set the size of the Black Window System ("mode con cols=100 lines=30");
	Note here x+2 y+1, in the black box is such a convention, no way int i;
		for (i = 0; i < i + + 2)//print up/down border {locateandprint (i, 0);
	Locateandprint (I, 26);
		for (i = 1; i < i++)//print left and right border {locateandprint (0, I);
	Locateandprint (i);

	}/* Create food/void Createfood () {//Create food success, jump out of loop int create_food_success_flag = TRUE;
		If the creation is unsuccessful, rebuild while (1) {int rand_x, rand_y;
			Do {//x random number 2-55 y random number 3-23 srand ((int) time (NULL));
			rand_x = rand ()% 53 + 2;
		rand_y = rand ()% 21 + 3; while (rand_x% 2!= 0);The/x needs to be 2 even, and the squares of x and y in the black box have limitations//to determine whether the resulting food overlaps with the snake body temp_ptr = head.next; while (temp_ptr!= NULL) {if (temp_ptr->x = = rand_x && temp_ptr->y = = rand_y) {//overlap, need to be recreated crea
				Te_food_success_flag = FALSE;
			Break
		} temp_ptr = temp_ptr->next;
		The coordinates of the//food overlap with the snake body, regenerating the food_node if (FALSE = = Create_food_success_flag) {continue;
		//created successfully, print Create_food_success_flag = TRUE in black box;
		food_node.x = rand_x;
		Food_node.y = rand_y;

		Locateandprint (rand_x, rand_y);
	Break }/* Initialize snake body/void intsnake (int snake_len, int start_x, int start_y) {for (int i = 0; i < Snake_len; i++) {Temp_
		PTR = (snake *) malloc (sizeof (snake));
		Temp_ptr->x = start_x;
		Temp_ptr->y = start_y;
		Start_x + 2;
		Head Insertion Method temp_ptr->next = Head.next;
		Head.next = temp_ptr;
	Output Initial snake body Locateandprint ((Head.next)->x, (Head.next)->y);

	}/* Game end/void Endgame () {//record score int snake_length = 0; Release the snake body malloc allocated Resources Snake * temp_ptr2;//here for clarity, introduce a third variable temP_PTR2, auxiliary variable temp_ptr2 can replace Temp_ptr = Head.next with Head.next;
		while (temp_ptr!= NULL) {temp_ptr2 = temp_ptr->next;
		Free (TEMP_PTR);
		Temp_ptr = TEMP_PTR2;
	snake_length++;

	//clear screen and output game failure reason System ("CLS"); if (bit_self = = Game_over_reason) {printf ("The snake Head and the snake body collide, failure.")
	\ n Score:%d\n ", snake_length-9); else if (Touch_wall = = Game_over_reason) {printf ("Hit the wall, failed.")

	\ n Score:%d\n ", snake_length-9);
} getchar ();
	/* Get the direction you typed/void Getentereddirection () {if (Getasynckeystate (Vk_oem_plus)) {speed = 25;
	else if (getasynckeystate (Vk_oem_minus)) {speed = 25;
	else if (getasynckeystate (vk_up) && Direction!= D) {direction = U;
	else if (getasynckeystate (vk_down) && Direction!= U) {direction = D;
	else if (getasynckeystate (vk_left) && Direction!= R) {direction = L;
	else if (getasynckeystate (vk_right) && Direction!= L) {direction = R; }/* Snake mobile/Void Snakemove () {//Save the original Head.next coordinate value int temp_x = head.Next->x, temp_y = head.next->y;
	To determine the direction, modify the value of the first node if (direction = = R) {head.next->x = 2;
	else if (direction = = L) {head.next->x = 2;
	else if (direction = = U) {head.next->y = 1;
	else if (direction = = D) {head.next->y = 1; //case1. The next node is food: the first node of the snake is coincident with the food node, and the new node is//case2 on the second node of the snake body. Next node is not food: new node at the second node of the snake//So can be merged snake * temp = (snake *) malloc (si
	Zeof (snake));
	Temp->x = temp_x;
	Temp->y = temp_y;
	Temp->next = head.next->next;

	Head.next->next = temp; Judge whether to wall if (head.next->x >= | | head.next->x <= 0 | | head.next->y <= 0 | | head.next->y >= 26)
		{Game_over_reason = bit_self;
	Endgame ();
		//Determine if the next node is food if (food_node.x = head.next->x && food_node.y = = head.next->y) {//Next node is food
	Re-create new food createfood ();
		
		else {//The next node is not food, then move the snake body//Print the box Locateandprint (Head.next->x, Head.next->y) in the first position of the snake forward;
		Temp_ptr = Head.next; while (Temp_ptr->next->next!= null) {//judge whether to bite itself if (temp_ptr->next->next!= null && temp_ptr->next->next->x = = (head.next)->x && temp_ptr->next->next->y = = (Head.next)->y) {Game_over_reason = BI
				t_self;
			Endgame ();
		} temp_ptr = temp_ptr->next;
		//Clear the end of the snake locateandclear (temp_ptr->next->x, temp_ptr->next->y);
	Free (temp_ptr->next);/Release snake tail node memory Temp_ptr->next = NULL;

	}/* Game loop/void Startgame () {//initial direction, default direction direction = R;

		while (1) {//Judge the keyboard input of the arrow keys, but note that "move direction for the press key does not work", left and right direction of empathy getentereddirection ();
	Show Snake body snakemove ()//Snake body moving sleep (speed);

	int main () {//Create map creatmap ();

	Initialization of the Snake body Intsnake (8, 4, 3);

	Create food Createfood ();

	Start the game loop constantly judging the direction of typing startgame ();
return 0; }

Vi. Summary: writing code is not one-step. I've gone through several steps in writing greedy snakes: 1. The first time is every time the snake body moves to change all the coordinates of the Snake body node, and clear screen, and then output all the nodes of the snake body. The problem is that the interface keeps flashing. 2. The second time is that each time the snake body moves the next node whether the food write two large pieces of code. For both cases. 3. The code that discovers the second two situations can insert a new node after the first header node to merge to have the current version. 4. There may be other improvements in the future.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.