你可以写一段贪吃蛇小游戏的代码吗?
时间: 2023-03-29 17:01:57 浏览: 60
可以的,以下是贪吃蛇小游戏的代码:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define MAX_X 20
#define MAX_Y 20
int map[MAX_X][MAX_Y];
int snake[MAX_X*MAX_Y][2];
int length = 3;
int direction = 1;
int score = ;
void init_map();
void init_snake();
void print_map();
void update_snake();
void update_direction();
void generate_food();
int main()
{
init_map();
init_snake();
generate_food();
while (1)
{
print_map();
update_direction();
update_snake();
Sleep(200);
system("cls");
}
return ;
}
void init_map()
{
int i, j;
for (i = ; i < MAX_X; i++)
{
for (j = ; j < MAX_Y; j++)
{
if (i == || i == MAX_X - 1 || j == || j == MAX_Y - 1)
{
map[i][j] = -1;
}
else
{
map[i][j] = ;
}
}
}
}
void init_snake()
{
int i;
for (i = ; i < length; i++)
{
snake[i][] = MAX_X / 2 + i;
snake[i][1] = MAX_Y / 2;
map[snake[i][]][snake[i][1]] = i + 1;
}
}
void print_map()
{
int i, j;
for (i = ; i < MAX_X; i++)
{
for (j = ; j < MAX_Y; j++)
{
if (map[i][j] == -1)
{
printf("#");
}
else if (map[i][j] == )
{
printf(" ");
}
else if (map[i][j] > )
{
printf("*");
}
if (j == MAX_Y - 1)
{
printf("\n");
}
}
}
printf("Score: %d\n", score);
}
void update_snake()
{
int i;
int tail[2];
tail[] = snake[length - 1][];
tail[1] = snake[length - 1][1];
map[tail[]][tail[1]] = ;
for (i = length - 1; i > ; i--)
{
snake[i][] = snake[i - 1][];
snake[i][1] = snake[i - 1][1];
map[snake[i][]][snake[i][1]] = i + 1;
}
switch (direction)
{
case 1:
snake[][1] -= 1;
break;
case 2:
snake[][] -= 1;
break;
case 3:
snake[][1] += 1;
break;
case 4:
snake[][] += 1;
break;
}
if (map[snake[][]][snake[][1]] == -1 || map[snake[][]][snake[][1]] > )
{
printf("Game over!\n");
exit();
}
if (snake[][] == food[] && snake[][1] == food[1])
{
length++;
score += 10;
generate_food();
}
map[snake[][]][snake[][1]] = 1;
}
void update_direction()
{
if (_kbhit())
{
switch (_getch())
{
case 'w':
if (direction != 3)
{
direction = 1;
}
break;
case 'a':
if (direction != 4)
{
direction = 2;
}
break;
case 's':
if (direction != 1)
{
direction = 3;
}
break;
case 'd':
if (direction != 2)
{
direction = 4;
}
break;
}
}
}
void generate_food()
{
int x, y;
do
{
x = rand() % (MAX_X - 2) + 1;
y = rand() % (MAX_Y - 2) + 1;
} while (map[x][y] != );
map[x][y] = -2;
food[] = x;
food[1] = y;
}