c++语言写贪吃蛇的代码
时间: 2023-04-03 15:00:40 浏览: 107
c++代码贪吃蛇游戏直接复制到vc6.0编译器即可.pdf
你好,以下是 C 语言写贪吃蛇的代码:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define MAX_X 20
#define MAX_Y 20
int x, y, fruit_x, fruit_y, score;
int gameover;
int tail_x[100], tail_y[100];
int ntail;
enum eDirection { STOP = , LEFT, RIGHT, UP, DOWN };
enum eDirection dir;
void Setup()
{
gameover = ;
dir = STOP;
x = MAX_X / 2;
y = MAX_Y / 2;
fruit_x = rand() % MAX_X;
fruit_y = rand() % MAX_Y;
score = ;
}
void Draw()
{
system("cls");
for (int i = ; i < MAX_X + 2; i++)
printf("#");
printf("\n");
for (int i = ; i < MAX_Y; i++)
{
for (int j = ; j < MAX_X; j++)
{
if (j == )
printf("#");
if (i == y && j == x)
printf("O");
else if (i == fruit_y && j == fruit_x)
printf("F");
else
{
int print = ;
for (int k = ; k < ntail; k++)
{
if (tail_x[k] == j && tail_y[k] == i)
{
printf("o");
print = 1;
}
}
if (!print)
printf(" ");
}
if (j == MAX_X - 1)
printf("#");
}
printf("\n");
}
for (int i = ; i < MAX_X + 2; i++)
printf("#");
printf("\n");
printf("Score: %d\n", score);
}
void Input()
{
if (_kbhit())
{
switch (_getch())
{
case 'a':
dir = LEFT;
break;
case 'd':
dir = RIGHT;
break;
case 'w':
dir = UP;
break;
case 's':
dir = DOWN;
break;
case 'x':
gameover = 1;
break;
}
}
}
void Logic()
{
int prev_x = tail_x[];
int prev_y = tail_y[];
int prev2_x, prev2_y;
tail_x[] = x;
tail_y[] = y;
for (int i = 1; i < ntail; i++)
{
prev2_x = tail_x[i];
prev2_y = tail_y[i];
tail_x[i] = prev_x;
tail_y[i] = prev_y;
prev_x = prev2_x;
prev_y = prev2_y;
}
switch (dir)
{
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
}
if (x > MAX_X || x < || y > MAX_Y || y < )
gameover = 1;
for (int i = ; i < ntail; i++)
{
if (tail_x[i] == x && tail_y[i] == y)
gameover = 1;
}
if (x == fruit_x && y == fruit_y)
{
score += 10;
fruit_x = rand() % MAX_X;
fruit_y = rand() % MAX_Y;
ntail++;
}
}
int main()
{
Setup();
while (!gameover)
{
Draw();
Input();
Logic();
Sleep(50);
}
return ;
}
阅读全文