贪吃蛇C++代码
今天来给大家上两个贪吃蛇C++代码
第一种:
#include<iostream>
#include<windows.h>
#include<conio.h>
#include<ctime>
using namespace std;
const int COLS = 22;
const int ROWS = 22;
const string S_WALL = "∷";
const string S_SPACE = " ";
const string S_HEAD = "●";
const string S_BODY = "⊙";
const string S_FOOD = "★";
int snake [COLS * ROWS][2];
int food_x, food_y;//苹果的坐标
int Score = 5;
bool gameOver = false;
bool isPosInSnake( int x , int y );
char ch = 'd';
HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
COORD coord;
void p_wall();
void p_snake();
void p_food();
void move( char ch );
void locate( int x, int y )
{
coord.X = x * 2;
coord.Y = y;
SetConsoleCursorPosition(hout, coord);
}
double random( double start , double end )//生成一个start到end之间的随机数
{
return start + ( end - start ) * rand() / ( RAND_MAX + 1.0 );
}
int main()
{
system("pause");
system ( "cls" );
//初始化屏幕的一些参数,隐藏光标
CONSOLE_CURSOR_INFO cursor_info = {1, 0};
SetConsoleCursorInfo(hout, &cursor_info);
snake [0][0] = 6;//蛇头的坐标
snake [0][1] = 2;
snake [1][0] = 5;//蛇的第二个关节
snake [1][1] = 2;
snake [2][0] = 4;//蛇的第二个关节
snake [2][1] = 2;
snake [3][0] = 3;//蛇的第三个关节
snake [3][1] = 2;
snake [4][0] = 2;//蛇的第四个关节
snake [4][1] = 2;
//初始化苹果位置
do
{
food_x = random( 3 , COLS - 2 );
food_y = random( 2 , ROWS - 2 );
}
while ( isPosInSnake( food_x , food_y ) );
p_wall();//调用绘制墙面
clock_t a , b;
while( true )//死循环
{
//初始化屏幕的一些参数,隐藏光标
CONSOLE_CURSOR_INFO cursor_info = {1, 0};
SetConsoleCursorInfo(hout, &cursor_info);
if( gameOver )
{
system ( "cls" );
cout << "Game Over!" << endl;
cout << "You lose!" << endl;
cout << "Score : " << Score << endl;
system("pause");
return 0;
}
p_snake();//调用绘制蛇头
p_food();//调用绘制苹果
a = clock();
while ( 1 )
{
b = clock();
if( b - a >= 230 )
{
break;
}
}
if( kbhit() )
{
char next_ch = getch();//死循环获取用户按下的字符
if( next_ch >= 'A' && next_ch <= 'Z' )
{
next_ch += 'a' - 'A';
}
if( ( 'd' == ch || 'a' == ch ) && ( next_ch == 'w' || next_ch == 's' ) )
{
ch = next_ch;
}
else if( ( 'w' == ch || 's' == ch ) && ( next_ch == 'a' || next_ch == 'd' ) )
{
ch = next_ch;
}
}
move( ch );//调整坐标的x,y位置
locate( 0 , COLS + 1 );
cout << "Now Score : " << Score;
}
}
bool isPosInSnake( int x , int y )
{
for( int i = 0; i < COLS * ROWS; i++ )
{
if( snake [i][0] == x && snake [i][1] == y )
{
return true;
}
}
return false;
}
void move( char ch )
{
int x = snake [0][0] , y = snake [0][1];
switch( ch )
{
case 'W' ://按下W,向上
case 'w' ://按下w,向上
y--;
break;
case 'S' ://按下S,向下
case 's' ://按下s,向下
y++;
break;
case 'A' ://按下A,向左
case 'a' ://按下a,向左
x--;
break;
case 'D' ://按下D,向右
case 'd' ://按下d,向右
x++;
break;
default :
return;
}
if( x < 2 || x > COLS - 1 || y < 2 || y > ROWS - 1 )//检测是否撞墙
{
gameOver = true;
return;
}
if( isPosInSnake( x , y ) )
{
gameOver = true;
return;
}
for( int i = COLS * ROWS - 1; i >= 1; i-- )//身体所有部位向前移
{
snake [i][0] = snake [i - 1][0];
snake [i][1] = snake [i - 1][1];
}
snake [0][0] = x; snake [0][1] = y;
if( x == food_x && y == food_y )//检测是否吃掉苹果
{
Score+=1;
//吃了苹果,分数加1
do
{
food_x = random( 3 , COLS - 2 );
food_y = random( 2 , ROWS - 2 );
}
while ( isPosInSnake( food_x , food_y ) );
}
else
{
for( int i = COLS * ROWS - 1; i >= 1; i-- )//删除尾巴节点
{
if( snake [i][0] > 0 )
{
locate( snake [i][0] , snake [i][1] );
cout << S_SPACE;
snake [i][0] = 0;
snake [i][1] = 0;
break;
}
}
}
}
void p_snake()//绘制蛇头+蛇身
{
for( int i = 0; i < COLS * ROWS; i++ )
{
if( snake [i][0] <= 0 )
{
break;
}
if( i == 0 )//绘制蛇头
{
locate( snake [i][0] , snake [i][1] );
cout << S_HEAD;
}
else//绘制蛇身
{
locate( snake [i][0] , snake [i][1] );
cout << S_BODY;
}
}
}
void p_wall()//绘制围墙
{
locate( 0 , 0 );
cout << endl;
for( int i = 1; i <= ROWS; i++ )
{
cout << " ";
for( int j = 1; j <= COLS; j++ )
{
if( i == 1 || i == ROWS || j == 1 || j == COLS )
{
cout << S_WALL;
}
else
{
cout << S_SPACE;
}
}
cout << endl;
}
cout << endl;
}
void p_food()//绘制苹果
{
locate( food_x , food_y );
cout << S_FOOD;
}
效果图
按任意键即可开始
第二种:
#include<stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>
#include <time.h>
#include <windows.h>
#define MAXWIDTH (30)
#define MAXHEIGHT MAXWIDTH
#define INITLEN (3)
struct{
char *ch;
int color;
char type;
}
charBorder = {"□", 4, 1},
charBg = {"■", 2, 2},
charSnake = {"★", 0xe, 3},
charFood = {"●", 0xc, 4};
struct{
char type;
int index;
}globalMap[MAXWIDTH][MAXHEIGHT];
struct{
int x;
int y;
} snakeMap[ (MAXWIDTH-2)*(MAXHEIGHT-2) ], scoresPostion;
int scores = 0;
int snakeMapLen = (MAXWIDTH-2)*(MAXHEIGHT-2);
int headerIndex, tailIndex; //蛇头蛇尾对应的snakeMap中的索引(下标)
HANDLE hStdin;
void setPosition(int x, int y){
COORD coord;
coord.X = 2*y;
coord.Y = x;
SetConsoleCursorPosition(hStdin, coord);
}
void setColor(int color){
SetConsoleTextAttribute(hStdin, color);
}
void createFood(){
int index, rang, x, y;
//产生随机数,确定 snakeMap 数组的索引
srand((unsigned)time(NULL));
if(tailIndex<headerIndex){
rang = headerIndex-tailIndex-1;
index = rand()%rang + tailIndex + 1;
}else{
rang = snakeMapLen - (tailIndex - headerIndex+1);
index = rand()%rang;
if(index>=headerIndex){
index += (tailIndex-headerIndex+1);
}
}
x = snakeMap[index].x;
y = snakeMap[index].y;
setPosition(x, y);
setColor(charFood.color);
printf("%s", charFood.ch);
globalMap[x][y].type=charFood.type;
}
//死掉
void die(){
int xCenter = MAXHEIGHT%2==0 ? MAXHEIGHT/2 : MAXHEIGHT/2+1;
int yCenter = MAXWIDTH%2==0 ? MAXWIDTH/2 : MAXWIDTH/2+1;
setPosition(xCenter, yCenter-5);
setColor(0xC);
printf("You die! Game Over!");
getch();
exit(0);
}
void move(char direction){
int newHeaderX, newHeaderY;
int newHeaderPreIndex;
int newHeaderPreX, newHeaderPreY;
int newHeaderPreType;
int oldTailX, oldTailY;
switch(direction){
case 'w':
newHeaderX = snakeMap[headerIndex].x-1;
newHeaderY = snakeMap[headerIndex].y;
break;
case 's':
newHeaderX = snakeMap[headerIndex].x+1;
newHeaderY = snakeMap[headerIndex].y;
break;
case 'a':
newHeaderX = snakeMap[headerIndex].x;
newHeaderY = snakeMap[headerIndex].y-1;
break;
case 'd':
newHeaderX = snakeMap[headerIndex].x;
newHeaderY = snakeMap[headerIndex].y+1;
break;
}
headerIndex = headerIndex==0 ? snakeMapLen-1 : headerIndex-1;
newHeaderPreIndex = globalMap[newHeaderX][newHeaderY].index;
newHeaderPreX = snakeMap[headerIndex].x;
newHeaderPreY = snakeMap[headerIndex].y;
snakeMap[headerIndex].x = newHeaderX;
snakeMap[headerIndex].y = newHeaderY;
globalMap[newHeaderX][newHeaderY].index = headerIndex;
snakeMap[newHeaderPreIndex].x = newHeaderPreX;
snakeMap[newHeaderPreIndex].y = newHeaderPreY;
globalMap[newHeaderPreX][newHeaderPreY].index = newHeaderPreIndex;
newHeaderPreType = globalMap[newHeaderX][newHeaderY].type;
//设置新蛇头类型
globalMap[newHeaderX][newHeaderY].type = charSnake.type;
// 判断是否出界或撞到自己
if(newHeaderPreType==charBorder.type || newHeaderPreType==charSnake.type ){
die();
}
//输出新蛇头
setPosition(newHeaderX, newHeaderY);
setColor(charSnake.color);
printf("%s", charSnake.ch);
//判断是否吃到食物
if(newHeaderPreType==charFood.type){ //吃到食物
createFood();
//更改分数
setPosition(scoresPostion.x, scoresPostion.y);
printf("%d", ++scores);
}else{
//老蛇尾坐标
oldTailX = snakeMap[tailIndex].x;
oldTailY = snakeMap[tailIndex].y;
//删除蛇尾
setPosition(oldTailX, oldTailY);
setColor(charBg.color);
printf("%s", charBg.ch);
globalMap[oldTailX][oldTailY].type = charBg.type;
tailIndex = (tailIndex==0) ? snakeMapLen-1 : tailIndex-1;
}
}
//下次移动的方向
char nextDirection(char ch, char directionOld){
int sum = ch+directionOld;
ch = tolower(ch);
if( (ch=='w' || ch=='a' || ch=='s' || ch=='d') && sum!=197 && sum!=234 ){
return ch;
}else{
return directionOld;
}
}
//暂停
char pause(){
return getch();
}
// 初始化
void init(){
// 设置相关变量
int x, y, i, index;
int xCenter = MAXHEIGHT%2==0 ? MAXHEIGHT/2 : MAXHEIGHT/2+1;
int yCenter = MAXWIDTH%2==0 ? MAXWIDTH/2 : MAXWIDTH/2+1;
CONSOLE_CURSOR_INFO cci; //控制台光标信息
//判断相关设置是否合理
if(MAXWIDTH<16){
printf("'MAXWIDTH' is too small!");
getch();
exit(0);
}
//设置窗口大小
system("mode con: cols=96 lines=32");
//隐藏光标
hStdin = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleCursorInfo(hStdin, &cci);
cci.bVisible = 0;
SetConsoleCursorInfo(hStdin, &cci);
//打印背景
for(x=0; x<MAXHEIGHT; x++){
for(y=0; y<MAXWIDTH; y++){
if(y==0 || y==MAXWIDTH-1 || x==0 || x==MAXHEIGHT-1){
globalMap[x][y].type = charBorder.type;
setColor(charBorder.color);
printf("%s", charBorder.ch);
}else{
index = (x-1)*(MAXWIDTH-2)+(y-1);
snakeMap[index].x= x;
snakeMap[index].y= y;
globalMap[x][y].type = charBg.type;
globalMap[x][y].index = index;
setColor(charBg.color);
printf("%s", charBg.ch);
}
}
printf("\n");
}
//初始化贪吃蛇
globalMap[xCenter][yCenter-1].type = globalMap[xCenter][yCenter].type = globalMap[xCenter][yCenter+1].type = charSnake.type;
headerIndex = (xCenter-1)*(MAXWIDTH-2)+(yCenter-1) - 1;
tailIndex = headerIndex+2;
setPosition(xCenter, yCenter-1);
setColor(charSnake.color);
for(y = yCenter-1; y<=yCenter+1; y++){
printf("%s", charSnake.ch);
}
//生成食物
createFood();
//设置程序信息
setPosition(xCenter-1, MAXWIDTH+2);
printf(" Apples : 0");
setPosition(xCenter, MAXWIDTH+2);
printf(" Author : xiao p");
setPosition(xCenter+1, MAXWIDTH+2);
printf("Copyright : c.biancheng.net");
scoresPostion.x = xCenter-1;
scoresPostion.y = MAXWIDTH+8;
}
int main(){
char charInput, direction = 'a';
init();
charInput = tolower(getch());
direction = nextDirection(charInput, direction);
while(1){
if(kbhit()){
charInput = tolower(getch());
if(charInput == ' '){
charInput = pause();
}
direction = nextDirection(charInput, direction);
}
move(direction);
Sleep(500);
}
getch();
return 0;
}
效果图