[C++] 贪吃蛇 DOS版
本帖最后由 mzflz 于 2014-9-20 08:43 编辑第一次在这版块发帖,呵呵,以前老感觉这版块是那些大牛们的地盘,所以只看没发。
这贪吃蛇程序说是C语言吧,其实也不是,因为这程序中用到了C++的引用(其实指针也行,只是懒得多改原来出现错误的代码),算法很简单,相信大家都能看懂。
本人能力有限,错误肯定是有的,望大牛们指教。
不多说了,上代码。
/ LazySnake.cpp : 定义控制台应用程序的入口点。
//贪吃蛇DOS版
#include "stdafx.h"
#include<windows.h>
#define MAX 100
#define UP 1
#define DOWN 2
#define LEFT 3
#define RIGHT 4
#define Head_X SnakeX
#define Head_Y SnakeY
const int Height = 30;
const int Width = 50;
const int Speed = 200/*ms*/;
const int ScoreX = 60, ScoreY = 15;
int HeadDirection = DOWN; //舌头方向
int SnakeX;
int SnakeY;
int SnakeLength =1;
int FoodX = rand()%Width;
int FoodY = rand()%Height;
inline BOOL isWin()
{
return (MAX < SnakeLength);
}
BOOL gotoxy(int x, int y)
{
COORD c={x,y};
return SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c);
}
void ArrayOffset(int &OldHeadX, int& OldHeadY, int& OldX, int& OldY)
{
for (int i = 1; i < SnakeLength; i++)
{
OldX = SnakeX;
OldY = SnakeY;
SnakeX = OldHeadX;
SnakeY = OldHeadY;
OldHeadX = OldX;
OldHeadY = OldY;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
SetConsoleTitleA("LazySnake By null");
for (int i = 0; i < Width; i++)
{
printf("-");
}
for (int i = 0; i < Height; i++)
{
gotoxy(0,i);
printf("|");
gotoxy(Width,i);
printf("|");
}
printf("\n");
for (int i = 0; i < Width; i++)
{
printf("-");
}
ZeroMemory(SnakeX,sizeof(SnakeX));
ZeroMemory(SnakeY,sizeof(SnakeY));
gotoxy(FoodX,FoodY);
printf("8");
Head_X = Width / 2;
Head_Y = Height / 2;
while (true)
{
if (GetAsyncKeyState(VK_LEFT))
HeadDirection = LEFT
;
if (GetAsyncKeyState(VK_RIGHT))
HeadDirection = RIGHT
;
if (GetAsyncKeyState(VK_UP))
HeadDirection = UP
;
if (GetAsyncKeyState(VK_DOWN))
HeadDirection = DOWN
;
static int OldHeadX,OldHeadY,OldX = OldHeadX,OldY = OldHeadY;
switch (HeadDirection)
{
case UP:
OldHeadX = Head_X;
OldHeadY = Head_Y;
Head_Y = Head_Y - 1;
ArrayOffset(OldHeadX, OldHeadY, OldX, OldY);
break;
case DOWN:
OldHeadX = Head_X;
OldHeadY = Head_Y;
Head_Y = Head_Y + 1;
ArrayOffset(OldHeadX, OldHeadY, OldX, OldY);
break;
case LEFT:
OldHeadX = Head_X;
OldHeadY = Head_Y;
Head_X = Head_X - 1;
ArrayOffset(OldHeadX, OldHeadY, OldX, OldY);
break;
case RIGHT:
OldHeadX = Head_X;
OldHeadY = Head_Y;
Head_X = Head_X + 1;
ArrayOffset(OldHeadX, OldHeadY, OldX, OldY);
break;
}
int Old_X, Old_Y;
if (Head_X < 0 || Head_X > Width||Head_Y<0||Head_Y>Height)
{
system("cls");
printf("Game Over\n");
system("pause");
}
if (Head_X == FoodX&&FoodY == Head_Y)
{
FoodX = rand() % Width;
FoodY = rand() % Height;
gotoxy(FoodX,FoodY);
printf("8");
SnakeLength++;
}
for (int i = 0; i < SnakeLength; i++)
{
gotoxy(SnakeX,SnakeY);
printf("0");
}
if (isWin())
{
printf("恭喜你! 你赢了!");
}
gotoxy(OldHeadX,OldHeadY);
printf(" ");
gotoxy(ScoreX,ScoreY);
printf("Score:%d",SnakeLength-1);
Sleep(Speed);
}
return 0;
}
非常喜欢这种这么萌的控制台小游戏。
如果不使用WIN32API那么就更好了。 嗯。不使用Win32API的话,就能移植到DOS、Linux什么的。 这蛇长得真好看
页:
[1]