用c语言在黑框框里写了一个贪食蛇,没有用SetConsoleCursorPosition,而是每次都把整个地图刷新一遍,所以会闪。
效果图:
源码如下:
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <windows.h> #include <conio.h> #define WID 10 #define HEI 30 #define WALL '+' #define SPACE ' ' #define BODY 's' #define FOOD 'f' int i,j,t; bool isgame; int map[WID][HEI]; struct Snake{ int len; int body[600]; }snake; int speed[2]={1,0}; int food; char *msg="move"; void createfood(){ while(food<2){ int x=rand()%(WID-2)+1; int y=rand()%(HEI-2)+1; if(map[x][y]==SPACE){ food++; map[x][y]=FOOD; } } } void initmap(){ for(i=0;i<WID;i++){ for(j=0;j<HEI;j++){ if(i==0||i==WID-1||j==0||j==HEI-1){ map[i][j]=WALL; } else{ map[i][j]=SPACE; } } } snake.len=1; snake.body[0]=WID/2; snake.body[1]=HEI/2; map[snake.body[0]][snake.body[1]]=BODY; food=0; createfood(); } void update(){ t=0; int head[2]={snake.body[snake.len*2-2],snake.body[snake.len*2-1]}; int next[2]={head[0]+speed[0],head[1]+speed[1]}; switch(map[next[0]][next[1]]){ case WALL: msg="hit the wall\npress any key to restart"; isgame=false; break; case FOOD: map[next[0]][next[1]]=BODY; snake.body[snake.len*2]=next[0]; snake.body[snake.len*2+1]=next[1]; snake.len++; food--; createfood(); msg="get the food"; break; case BODY: msg="hit self \npress any key to restart"; isgame=false; break; default: int node[2]={snake.body[0],snake.body[1]}; map[node[0]][node[1]]=SPACE; for(i=0;i<snake.len-1;i++){ snake.body[2*i]=snake.body[2*(i+1)]; snake.body[2*i+1]=snake.body[2*(i+1)+1]; } snake.body[2*i]=next[0]; snake.body[2*i+1]=next[1]; map[next[0]][next[1]]=BODY; msg="move"; break; } } void move(){ char ch; while(_kbhit()){ ch=getch(); } switch(ch){ case 'w': case 'W': if(speed[0]==-1){ update(); } else if(speed[0]!=1){ speed[0]=-1; speed[1]=0; } //上 break; case 'a': case 'A': if(speed[1]==-1){ update(); } else if(speed[1]!=1){ speed[0]=0; speed[1]=-1; } //左 break; case 's': case 'S': if(speed[0]==1){ update(); } else if(speed[0]!=-1){ speed[0]=1; speed[1]=0; } //下 break; case 'd': case 'D': if(speed[1]==1){ update(); } else if(speed[1]!=-1){ speed[0]=0; speed[1]=1; } //右 break; } t++; if(t>10){ update(); } } void draw(){ system("cls"); char s[350]; int n=0; for(i=0;i<WID;i++){ for(j=0;j<HEI;j++){ s[n]=map[i][j]; n++; } s[n]='\n'; n++; } s[n]='\0'; printf("%s\n%s",s,msg); } int main(){ initmap(); draw(); t=0; isgame=true; while(1){ if(isgame){ move(); draw(); } else{ getchar(); initmap(); t=0; isgame=true; draw(); } Sleep(20); } getchar(); return 0; }
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。