- # include <stdio.h>
- # include <stdlib.h>
- # include <time.h>
- # include <conio.h>
- # include <windows.h>
- int x[10]={5,5,5},y[10]={5,6,7},skx = 5,sky = 7,len = 3,sp = 201,ch = 'd',fdx,fdy,i,f,m = 23,n = 79;//other
- void gotoxy(int y, int x)//goto xy
- {
- COORD pos = {x,y};
- HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
- SetConsoleCursorPosition(hOut, pos);
- }
- void food()//setfood
- {
- do{f = 0;
- fdx = rand()%m,fdy = rand()%n;
- for(i=1;i<len;i++)
- if(fdx==x[i] && fdy==y[i])
- f = 1;
- }while(f);//if xy same
- gotoxy(fdx,fdy),putchar('&');
- }
- void show()//print
- {
- gotoxy(x[0],y[0]),putchar(' ');
- for(i=1;i<len;i++)//show
- gotoxy(x[i],y[i]),putchar('*');
- gotoxy(skx,sky),putchar('#');
- Sleep(sp);//wait
- }
- void move()//move snake
- {
- if(kbhit()) ch = getch();//if getch
- if(ch=='W' || ch=='w') skx--;//change direction
- else if(ch=='S' || ch=='s') skx++;
- else if(ch=='A' || ch=='a') sky--;
- else sky++;
- for(i=1;i<len;i++)//change xy
- x[i-1] = x[i],y[i-1] = y[i];
- x[len-1] = skx,y[len-1] = sky;
- if(skx==fdx && sky==fdy)//if eat
- {
- len++;
- for(i=len;i>=1;i--)
- x[i] = x[i-1],y[i] = y[i-1];
- food();
- if((sp=(sp-20)) < 0)
- sp+=20;
- }
- }
- void lost()//if lost
- {
- for(i=1;i<len-1;i++)//itself
- if(skx==x[i] && sky==y[i])
- printf("you knock into yourself!Created by Lxbs."),Sleep(5000),exit(1);
- if(sky<0 || skx<0 || skx>m || sky>n)//wall
- printf("you knock into the wall!Created by Lxbs."),Sleep(5000),exit(2);
- }
- int main()//begin
- {
- SetConsoleTitle("Ì°³ÔÉßV1.2 - by Á÷ÐDz»ËÀ");
- srand((unsigned)time(NULL));//full rand
- food();
- show();
- while(1)//main while
- {
- move();
- show();
- lost();
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/1910201513840.html
来源: http://www.codesnippet.cn/detail/1910201513840.html