能用c语言编写一段贪吃蛇的代码吗
时间: 2023-03-20 14:03:39 浏览: 102
C语言贪吃蛇源代码
5星 · 资源好评率100%
可以,以下是一份简单的C语言贪吃蛇代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define MAP_WIDTH 20
#define MAP_HEIGHT 20
int snakeX[100], snakeY[100], snakeLen = 3;
int foodX, foodY, score = 0;
int directionX = 1, directionY = 0;
int map[MAP_HEIGHT][MAP_WIDTH] = {0};
void drawMap(){
system("cls");
printf("Score: %d\n", score);
for(int i = 0; i <= MAP_HEIGHT; i++){
for(int j = 0; j <= MAP_WIDTH; j++){
if(map[i][j] == 1) printf("*");
else if(i == 0 || j == 0 || i == MAP_HEIGHT || j == MAP_WIDTH) printf("#");
else if(i == foodY && j == foodX) printf("$");
else printf(" ");
}
printf("\n");
}
}
void generateFood(){
foodX = rand() % (MAP_WIDTH - 2) + 1;
foodY = rand() % (MAP_HEIGHT - 2) + 1;
if(map[foodY][foodX] == 1) generateFood();
}
int main(){
snakeX[0] = 3;
snakeY[0] = 1;
map[snakeY[0]][snakeX[0]] = 1;
generateFood();
drawMap();
while(1){
Sleep(100);
if(kbhit()){
char c = getch();
if(c == 'w') directionX = 0, directionY = -1;
else if(c == 'a') directionX = -1, directionY = 0;
else if(c == 's') directionX = 0, directionY = 1;
else if(c == 'd') directionX = 1, directionY = 0;
}
int nextX = snakeX[snakeLen-1] + directionX;
int nextY = snakeY[snakeLen-1] + directionY;
if(nextX == 0 || nextX == MAP_WIDTH || nextY == 0 || nextY == MAP_HEIGHT) break;
if(map[nextY][nextX] == 1) break;
if(nextX == foodX && nextY == foodY){
map[nextY][nextX] = 1;
snakeX[snakeLen] = nextX;
snakeY[snakeLen] = nextY;
snakeLen++;
score += 10;
generateFood();
}else{
map[snakeY[0]][snakeX[0]] = 0;
for(int i = 0; i < snakeLen - 1; i++){
snakeX[i] = snakeX[i + 1];
snakeY[i] = snakeY[i + 1];
}
snakeX[snakeLen-1] = nextX;
snakeY[snakeLen-1] = nextY;
map[nextY][nextX] = 1;
}
drawMap();
}
printf("Game Over! Score: %d\n", score);
return 0;
}
```
阅读全文