请帮我用c语言编写一个贪吃蛇游戏
时间: 2023-09-15 21:19:00 浏览: 90
好的,我可以帮您编写一个简单的贪吃蛇游戏。以下是C语言的代码:
```c
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#include <Windows.h>
#define LEFT 75
#define RIGHT 77
#define UP 72
#define DOWN 80
int length;
int score;
int headX, headY;
int foodX, foodY;
int tailX[100], tailY[100];
int map[20][20];
int gameOver;
void initialize() {
length = 1;
score = 0;
headX = 10;
headY = 10;
foodX = rand() % 20;
foodY = rand() % 20;
gameOver = 0;
}
void drawMap() {
system("cls");
printf("Score: %d\n\n", score);
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
if (i == headY && j == headX) {
printf("O");
} else if (i == foodY && j == foodX) {
printf("*");
} else {
int print = 0;
for (int k = 0; k < length; k++) {
if (tailX[k] == j && tailY[k] == i) {
printf("o");
print = 1;
}
}
if (!print) {
printf(" ");
}
}
}
printf("\n");
}
}
void input() {
if (_kbhit()) {
switch (_getch()) {
case LEFT:
if (map[headY][headX - 1] == 1) {
gameOver = 1;
} else {
headX--;
}
break;
case RIGHT:
if (map[headY][headX + 1] == 1) {
gameOver = 1;
} else {
headX++;
}
break;
case UP:
if (map[headY - 1][headX] == 1) {
gameOver = 1;
} else {
headY--;
}
break;
case DOWN:
if (map[headY + 1][headX] == 1) {
gameOver = 1;
} else {
headY++;
}
break;
}
}
}
void update() {
if (headX == foodX && headY == foodY) {
score += 10;
length++;
foodX = rand() % 20;
foodY = rand() % 20;
for (int i = length - 1; i > 0; i--) {
tailX[i] = tailX[i - 1];
tailY[i] = tailY[i - 1];
}
tailX[0] = headX;
tailY[0] = headY;
}
for (int i = length - 1; i > 0; i--) {
tailX[i] = tailX[i - 1];
tailY[i] = tailY[i - 1];
}
tailX[0] = headX;
tailY[0] = headY;
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
if ((i == 0 || i == 19) || (j == 0 || j == 19)) {
map[i][j] = 1;
} else {
map[i][j] = 0;
}
}
}
for (int i = 0; i < length; i++) {
map[tailY[i]][tailX[i]] = 1;
}
}
int main() {
srand(time(NULL));
char playAgain = 'y';
while (playAgain == 'y') {
initialize();
while (!gameOver) {
drawMap();
input();
update();
Sleep(100);
}
printf("\nGame Over!\nPlay again? (y/n)\n");
scanf(" %c", &playAgain);
}
return 0;
}
```
请注意,这只是一个简单的实现,可能需要优化和改进。如果您有任何问题或建议,请随时问我 :)
阅读全文