写一个贪吃蛇c++程序
时间: 2023-05-17 19:06:04 浏览: 57
非常感谢您的提问!以下是一个简单的贪吃蛇C程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#define WIDTH 30
#define HEIGHT 20
int snake[WIDTH * HEIGHT][2];
int head, tail;
int food[2];
int score;
int direction;
int gameover;
void init() {
head = 0;
tail = 0;
snake[head][0] = WIDTH / 2;
snake[head][1] = HEIGHT / 2;
food[0] = rand() % WIDTH;
food[1] = rand() % HEIGHT;
score = 0;
direction = 'w';
gameover = 0;
}
void draw() {
system("cls");
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (i == snake[head][1] && j == snake[head][0]) {
printf("O");
} else if (i == food[1] && j == food[0]) {
printf("X");
} else {
int flag = 0;
for (int k = tail; k <= head; k++) {
if (i == snake[k][1] && j == snake[k][0]) {
printf("o");
flag = 1;
break;
}
}
if (!flag) {
printf(" ");
}
}
}
printf("\n");
}
printf("Score: %d\n", score);
}
void update() {
int x = snake[head][0];
int y = snake[head][1];
switch (direction) {
case 'w': y--; break;
case 's': y++; break;
case 'a': x--; break;
case 'd': x++; break;
}
if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT) {
gameover = 1;
return;
}
for (int i = tail; i <= head; i++) {
if (x == snake[i][0] && y == snake[i][1]) {
gameover = 1;
return;
}
}
if (x == food[0] && y == food[1]) {
score++;
food[0] = rand() % WIDTH;
food[1] = rand() % HEIGHT;
} else {
tail++;
}
head++;
snake[head][0] = x;
snake[head][1] = y;
}
int main() {
srand(time(NULL));
init();
while (!gameover) {
draw();
update();
if (_kbhit()) {
direction = _getch();
}
Sleep(100);
}
printf("Game Over! Score: %d\n", score);
return 0;
}
```
希望这个程序能够帮到您!