直接上代码了
#include<iostream>
#include"ff.h"
#include<time.h>
#include<windows.h>
void main()
{
srand((unsigned int)time(NULL));
init();
while(1)
{
MoveCursor(0, 0);
draw();
if(lose)
{
std::cout<<"YOU LOSE";
system("pause");
return ;
}
run() ;
Sleep(100);
}
}
void MoveCursor(int x, int y);
extern bool win ;
extern bool lose ;
void init();
void draw();
void run();
#include<iostream>
#include<windows.h>
#include"ff.h"
#define W 20
#define H 20
#define S (W*H)
struct SNAKE
{
int x ;
int y ;
bool you ;
};
int Slen = 3 ;
SNAKE snake[200]={} ;
int map[S] = {};
int Tmap[S]={};
int dirx[4]={0,0,-1,1};
int diry[4]={-1,1,0,0};
char *arr[]={" ","■","●","□"};//卍
int dir = 0 ;
int food ;
bool fafood = true ;
bool win = false ;
bool lose = false ;
int ZApl = 10 ;
void MoveCursor(int x, int y)
{
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);///获取输出流句柄
COORD coord;///定义COORD结构体(包含X和Y两个成员)
coord.X = x * 2; ///设置结构体X轴
coord.Y = y; ///设置结构体Y轴
SetConsoleCursorPosition(hOut, coord);///设置光标位置
CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };///修改光标宽带和显示
SetConsoleCursorInfo(hOut, &cursor_info);///设置光标不可见
}
void init()
{
for(int i = 0 ; i < S ; ++i)
{
snake[i].you = false ;
}
snake[0].x = 9 ;
snake[0].y = 9 ;
snake[0].you = true ;
snake[1].x = 8 ;
snake[1].y = 9 ;
snake[1].you = true ;
snake[2].x = 7 ;
snake[2].y = 9 ;
snake[2].you = true ;
while(ZApl)
{
int a = rand()%S ;
if(map[a] == 0 )
map[a] = 1 ;
else
ZApl++;
--ZApl ;
}
}
void draw ()
{
memset(Tmap,1,S*4);
memcpy(Tmap,map,S*4);
for(int i = 0 ; i < 200; ++i)
{
if(snake[i].you == true )
Tmap[snake[i].x+snake[i].y*W] = 2 ;
}
for(int i = 0 ; i < S ; ++i)
{
std::cout<<arr[Tmap[i]];
if(i%W == W-1)
std::cout<<std::endl ;
}
if(fafood)
{
do
{
food = rand()%S;
}while(Tmap[food] != 0);
map[food] = 3 ;
fafood = false ;
}
}
void run()
{
if((GetAsyncKeyState('W') & 1) && dir != 1)dir = 0 ;
else if((GetAsyncKeyState('S') & 1) && dir != 0)dir = 1 ;
else if((GetAsyncKeyState('A') & 1) && dir != 3)dir = 2 ;
else if((GetAsyncKeyState('D') & 1) && dir != 2)dir = 3 ;
SNAKE next;
next.x = snake[0].x +dirx[dir] ;
next.y = snake[0].y +diry[dir] ;
next.you = true ;
if(next.x == -1)next.x = W-1 ;
if(next.x == W)next.x = 0 ;
if(next.y == -1)next.y = H-1 ;
if(next.y == H) next.y = 0 ;
if(map[next.x + next.y*W] == 3 )
{
map[next.x + next.y*W] = 0 ;
fafood = true ;
Slen++;
}
if(map[next.x + next.y*W] == 1 || Tmap[next.x + next.y*W] == 2)
{
lose = true ;
}
if(Slen == 20)
{
win = true ;
}
for(int i = Slen - 1 ; i > 0 ; --i)
{
snake[i] = snake[i-1] ;
}
snake[0] = next ;
}