1.游戏界面
2.游戏说明
贪吃蛇游戏按键说明:
按方向键上下左右,可以实现蛇移动方向的改变:
3.程序源代码
代码如下(示例):
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
#include <time.h>
#define width 60
#define hight 25
#define SNAKESIZE 200
int key = 72;
int changeflag = 1;
int speed = 0;
struct {
int len;
int x[SNAKESIZE];
int y[SNAKESIZE];
int speed;
}snake;
struct
{
int x; int y;
}food;
void gotoxy(int x, int y)
{
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void drawmap()
{
for (int _y = 0; _y < hight; _y++)
{
for (int x = 0; x < width; x += 2)
{
if (x == 0 || _y == 0 || _y == hight - 1 || x == width - 2)
{
gotoxy(x, _y);
printf("■");
}
}
}
snake.len = 3;
snake.x[0] = width / 2;
snake.y[0] = hight / 2;
gotoxy(snake.x[0], snake.y[0]);
printf("■");
for (int i = 1; i < snake.len; i++)
{
snake.x[i] = snake.x[i - 1];
snake.y[i] = snake.y[i - 1] + 1;
gotoxy(snake.x[i], snake.y[i]);
printf("■");
}
food.x = 20;
food.y = 20;
gotoxy(food.x, food.y);
printf("○");
}
void snake_move()
{
int history_key = key;
if (_kbhit())
{
fflush(stdin);
key = _getch();
key = _getch();
}
if (changeflag == 1)
{
gotoxy(snake.x[snake.len - 1], snake.y[snake.len - 1]);
printf(" ");
}
for (int i = snake.len - 1; i > 0; i--)
{
snake.x[i] = snake.x[i - 1];
snake.y[i] = snake.y[i - 1];
}
if (history_key == 72 && key == 80) key = 72;
if (history_key == 80 && key == 72) key = 80;
if (history_key == 75 && key == 77) key = 75;
if (history_key == 77 && key == 75) key = 77;
switch (key)
{
case 72:snake.y[0]--; break;
case 75:snake.x[0] -= 2; break;
case 77:snake.x[0] += 2; break;
case 80:snake.y[0]++; break;
}
gotoxy(snake.x[0], snake.y[0]);
printf("■");
gotoxy(0, 0);
changeflag = 1;
}
void creatfood()
{
if (snake.x[0] == food.x && snake.y[0] == food.y)
{
changeflag = 0;
snake.len++;
if (speed <= 100)speed += 10;
while (1)
{
srand((unsigned int)time(NULL));
food.x = rand() % (width - 6) + 2;
food.y = rand() % (hight - 2) + 1;
for (int i = 0; i < snake.len; i++)
{
if (food.x == snake.x[i] && food.y == snake.y[i])
break;
}
if (food.x % 2 == 0) break;
}
gotoxy(food.x, food.y); printf("○");
}
}
bool Gameover()
{
if (snake.x[0] == 0 || snake.x[0] == width - 2)return false;
if (snake.y[0] == 0 || snake.y[0] == hight - 1) return false;
if (snake.len == SNAKESIZE) return false;
for (int i = 1; i < snake.len; i++)
{
if (snake.x[0] == snake.x[i] && snake.y[0] == snake.y[i])
return false;
}
return true;
}
int main()
{
system("mode con cols=60 lines=27");
drawmap();
while (Gameover())
{
snake_move();
creatfood();
Sleep(350 - speed);
}
return 0;
}
感谢阅读,如有不足之处,欢迎来指正。谢谢!
|