C++写个贪吃蛇

/*通过自己按移动
struct name{
char sname[10];
};
struct person{
struct name *myname;
};
int main()
{
    struct person wang;
    scanf("%s",&((wang.myname)->sname));
    //fflush(stdin);
    printf("%s\n",(wang.myname)->sname);
}
*/
#include<iostream>
#include<conio.h>
#include<windows.h>
#include<ctime>
#include<stdlib.h>
using namespace std;
struct node {
	int x,y;
	struct node *next;
};
int cnt,fx,fy;// 蛇长
node *tou,*wei;//头、尾指针
char dir;
void gotoXY(short x, short y) {
	COORD pos = {x,y};
	HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
	SetConsoleCursorPosition(out,pos);
}
void creatfood() {
	fx=rand()%36;
	if(fx%2==0)
		fx+=2;
	else
		fx++;
	fy=rand()%18;
	fy++;
	gotoXY(fx,fy);
	cout<<"卍";
}
void fang() {
	gotoXY(5,20);
	char t;
	while(kbhit()) {
		t=getch();
		if(t=='w'||t=='W')
			if(dir!='s') dir='w';
		if(t=='a'||t=='A')
			if(dir!='d') dir='a';
		if(t=='s'||t=='S')
			if(dir!='w') dir='s';
		if(t=='d'||t=='D')
			if(dir!='a') dir='d';
	}
}
void init() {
	system("cls");
	dir='s';
	cnt=3;
	node* p;
	tou=p=(node*)malloc(sizeof(node));
	p->x=4;
	p->y=1;
	p->next=(node*)malloc(sizeof(node));
	p=p->next;
	p->x=4;
	p->y=2;
	p->next=(node*)malloc(sizeof(node));
	p=p->next;
	p->x=4;
	p->y=3;
	p->next=NULL;
	wei=p;
	int i;
	for(i=0; i<40; i+=2) {
		gotoXY(i,0);
		cout<<"■";
		gotoXY(i,19);
		cout<<"■";
	}
	for(i=0; i<20; i++) {
		gotoXY(0,i);
		cout<<"■";
		gotoXY(38,i);
		cout<<"■";
	}
	gotoXY(46,5);
	cout<<"按a,w,s,d移动,仅供学习之用!";
	creatfood();
	gotoXY(46,6);
	cout<<"蛇长:"<<cnt;
}
void move() {
	node *p;
	int x,y;
	if(dir=='w') {
		x=wei->x;
		y=wei->y-1;
	}
	if(dir=='s') {
		x=wei->x;
		y=wei->y+1;
	}
	if(dir=='a') {
		x=wei->x-2;
		y=wei->y;
	}
	if(dir=='d') {
		x=wei->x+2;
		y=wei->y;
	}
	gotoXY(x,y);
	cout<<"★";
	if(wei->x==fx&&wei->y==fy) {
		cnt++;
		gotoXY(46,6);
		cout<<"蛇长:"<<cnt;
		creatfood();
		p=(node*)malloc(sizeof(node));
		p->x=x;
		p->y=y;
		wei->next=p;
		wei=p;
		wei->next=NULL;
	} else {
		if(tou->x!=fx||tou->y!=fy) {
			gotoXY(tou->x,tou->y);
			cout<<"  ";//蛇尾走过的地方要清空
		}
		tou->x=x;
		tou->y=y;
		wei->next=tou;
		tou=tou->next;
		wei=wei->next;
		wei->next=NULL;
	}
	if(wei->x>=38||wei->y>=19||wei->y<=0||wei->x<=0) {
		MessageBox(NULL,"你挂了,游戏重新开始","糟糕!",MB_OK);
		init();
		return;
	}
	p=tou;
	while(p->next) {
		if(wei->x==p->x&&wei->y==p->y) {
			MessageBox(NULL,"你挂了,游戏重新开始","糟糕!",MB_OK);
			init();
			return;
		}
		p=p->next;
	}
}
void game() {
	init();
	while(1) {
		Sleep(200);
		fang();
		move();
	}
}
int main() {
	srand((unsigned)time(0));
	system("color 12");
	game();
}

博客链接:https://blog.csdn.net/update7/article/details/56847485

猜你喜欢

转载自blog.csdn.net/salmonwilliam/article/details/82114020