C + + Implementation of snake game detailed steps and practical demonstrations

Source: Internet
Author: User
Tags random seed
Learning C + + process to do a small program, relatively simple, only to achieve the most basic functions of the snake game. Upload code as a record of learning, but also for other students to provide as a small reference. The implementation environment is: Microsoft Visual c++6.0 integrated development environment.

#include <iostream> #include <cmath> #include <cstdlib> #include <cstdio> #include <ctime > #include <conio.h> #include <windows.h>using namespace std;/* cursor positioning */handle hout = GetStdHandle (std_ Output_handle); COORD coord;void Locate (int x, int y) {COORD. X = Y;coord. Y = x; SetConsoleCursorPosition (Hout,coord);};/ * Cursor Hide */void hide () {Console_cursor_info cursor_info = {1,0};//bvisible=0; hide Cursor Setconsolecursorinfo (Hout, &cursor_ Info)//Get cursor state}/* generate random number */double (double start, double end) {return start + (End-start) *rand ()/(rand_max+1.0);// Generates a number, greater than or equal to start, less than end;}/* defines the length and width of the map */int m, n;/* defines the snake's lengths, coordinates, directions, location of the food */struct node{int x, y; snake[1000];//snake coordinates int snake_length, dir;//snake length, direction node Food;int direct[4][2] = {{ -1,0}, {1,0}, {0,-1}, {0,1}};//location of food/* output Out of the fence: a rectangular box */void Print_wall () {//Output First line "----------" cout << ""; for (int i = 1; I <= N; i++) {cout << "-";} cout << endl;//Output first column "|", middle input space, last column output "|" for (int j = 0; J <= M-1; j + +) {cout << "|"; for (int i = 1; I <= N; i++) cout << ""; cout << "|" << Endl;} cout << "";//Output The last line "----------" for (int i = 1; I <= n; i++) cout << "-";} /* First output snake, where snake[0] represents the outer shape of the head *///snake: "@*****" void Print_snake () {locate (SNAKE[0].X,SNAKE[0].Y); cout << "@"; for (int i = 1; i < snake_length-1; i++) {Locate (snake[i].x, snake[i].y); cout << "*";}} /* Determine if hitting the wall or if the head touches any part of the body, the game fails */bool Is_correct () {if (snake[0].x = = 0 | | snake[0].y = 0 | | snake[0].x = m + 1 | | snak E[0].y = = n + 1) return false;//head touches edge for (int i = 1; I <= snake_length-1; i++) if (snake[0].x = snake[i].x &&am  P Snake[0].y = = snake[i].y) return false;//the head touches any part of the body return true; /* Randomly generated food location */bool Print_food () {srand (unsigned) time (0));//random seed bool E;while (1) {e = True;int i = (int) random (0,m) +1;int j = (int) random (0,n) +1;food.x = i; FOOD.Y = j;//Food location random for (int k = 0; k <= snake_length-1; k++)//food cannot appear anywhere in the body of the snake {if (snake[k].x = = Food.x &&amp  ;   Snake[k].y = = Food.y) {e= false; BReak; }}if (e) break;} Mark in place of food, food symbol "$"; locate (food.x,food.y); cout << "$"; return true; /* Snake advance */bool go_ahead () {node Tmp;bool e = false;tmp = snake[snake_length-1];//snake tail for (int i = snake_length-1; I >= 1;i --) {Snake[i] = snake[i-1];//move back one}snake[0].x + = Direct[dir][0];snake[0].y + direct[dir][1];locate (snake[1].x, snake[1 ].Y);//position to the back of the head cout << "*";/* Eat food */if (snake[0].x = = Food.x&&snake[0].y = food.y) {snake_length++;e = TRUE;SNAKE[SNAKE_LENGTH-1] = tmp;} /* Output at this time Snake state */if (!e) {Locate (tmp.x, tmp.y); cout << "";} Elseprint_food (); Locate (snake[0].x, snake[0].y); cout << "@";/*** if self-collision ***/if (!is_correct ()) {System ("CLS"); cout << "You lose!" << Endl << "Length:" << snake_length << Endl;return false;} return true;} int main () {//Game tip: cout << "--------------------snake---------------------" << endl;cout << "Please enter two number first, Represents the size of the map. "<< endl;cout <<" Please note the window size to avoid dislocation. The recommended window is set to maximum. << endl;cout <&Lt Select the difficulty. Please enter 1 numbers in 1-10, 1 The simplest, 10 is the hardest "<< endl;cout <<" then enter the game screen, with the direction key control direction. Have a good game! "<< endl;cout <<"- ----------------------------------------------"<< endl;cin >> m >> n;if (M < | | | n < ten | | m&gt ; 25 | | N&GT;40) {cout << "ERROR" << endl;system ("pause"); return 0;} Input difficulty factor: 1-10;int hard;cin >> hard;if (hard <= 0 | |) {cout << "ERROR" << endl;system ("Pa Use "); return 0;}  Data initialization: Snake position, length, direction snake_length = 5;//length clock_t A, B;char ch;double hard_len;for (int i = 0; I <= 4; i++)//Location {snake[i].x = 1;snake[i].y = 5-i;} DIR = 3;//Direction//output original map, food and Snake system ("cls"), Hide ();p rint_wall ();p rint_food ();p rint_snake ();//at (0,m+2) out display length: Locate (M + 2 , 0); cout << "now Length:";//Start Game while (1) {/* difficulty increases with length increase */hard_len = (double) snake_length/(double) (m*n);/* Adjust time, The unit is ms*/a = Clock (), while (1) {b = clock (), if (b-a >= (int) (400-30 * Hard) * (1-SQRT (Hard_len))); Receives the direction of the keyboard input//https://blog.csdn.net/wenweimin/artiCle/details/105561if (_kbhit ()) {ch = _getch (); if (ch = = -32) {ch = _getch (); switch (CH) {case 72:if (dir = = 2 | | dir = = 3) di R = 0; Break;case 80:if (dir = = 2 | | dir = = 3) dir = 1; Break;case 75:if (dir = = 0 | | dir = = 1) dir = 2; Break;case 77:if (dir = = 0 | | dir = = 1) dir = 3; Break;}}} Forward if (!go_ahead ()) break;//output at this time locate (M + 2, n); cout << snake_length;} System ("pause"); return 0;}
Related Article

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.