用c++写一个贪吃蛇游戏
时间: 2023-04-01 20:04:25 浏览: 79
好的,我可以回答这个问题。以下是一个简单的贪吃蛇游戏的 C 语言代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 20
#define HEIGHT 20
#define INIT_LENGTH 3
int score = ;
int speed = 200;
typedef struct {
int x;
int y;
} Point;
typedef struct {
Point head;
Point body[WIDTH * HEIGHT];
int length;
int direction;
} Snake;
typedef struct {
Point position;
int exist;
} Food;
void gotoxy(int x, int y) {
COORD pos = {x, y};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
void initSnake(Snake *snake) {
snake->head.x = WIDTH / 2;
snake->head.y = HEIGHT / 2;
snake->length = INIT_LENGTH;
snake->direction = 'w';
for (int i = ; i < INIT_LENGTH; i++) {
snake->body[i].x = snake->head.x;
snake->body[i].y = snake->head.y + i + 1;
}
}
void initFood(Food *food) {
food->exist = ;
}
void drawMap() {
for (int i = ; i <= HEIGHT + 1; i++) {
for (int j = ; j <= WIDTH + 1; j++) {
if (i == || i == HEIGHT + 1 || j == || j == WIDTH + 1) {
printf("#");
} else {
printf(" ");
}
}
printf("\n");
}
}
void drawSnake(Snake *snake) {
gotoxy(snake->head.x, snake->head.y);
printf("@");
for (int i = ; i < snake->length; i++) {
gotoxy(snake->body[i].x, snake->body[i].y);
printf("*");
}
}
void drawFood(Food *food) {
if (food->exist) {
gotoxy(food->position.x, food->position.y);
printf("$");
}
}
void generateFood(Food *food, Snake *snake) {
int x, y;
do {
x = rand() % WIDTH + 1;
y = rand() % HEIGHT + 1;
} while (x == snake->head.x && y == snake->head.y);
food->position.x = x;
food->position.y = y;
food->exist = 1;
}
void updateSnake(Snake *snake, Food *food) {
Point tail = snake->body[snake->length - 1];
for (int i = snake->length - 1; i > ; i--) {
snake->body[i] = snake->body[i - 1];
}
snake->body[] = snake->head;
switch (snake->direction) {
case 'w':
snake->head.y--;
break;
case 's':
snake->head.y++;
break;
case 'a':
snake->head.x--;
break;
case 'd':
snake->head.x++;
break;
}
if (snake->head.x == food->position.x && snake->head.y == food->position.y) {
snake->length++;
score++;
generateFood(food, snake);
if (score % 5 == ) {
speed -= 20;
}
}
for (int i = ; i < snake->length; i++) {
if (snake->head.x == snake->body[i].x && snake->head.y == snake->body[i].y) {
printf("\a");
printf("\nGame Over!\n");
printf("Your score: %d\n", score);
exit();
}
}
if (snake->head.x == || snake->head.x == WIDTH + 1 || snake->head.y == || snake->head.y == HEIGHT + 1) {
printf("\a");
printf("\nGame Over!\n");
printf("Your score: %d\n", score);
exit();
}
}
void updateDirection(Snake *snake) {
if (_kbhit()) {
char ch = _getch();
if (ch == 'w' || ch == 's' || ch == 'a' || ch == 'd') {
if (abs(ch - snake->direction) != 2) {
snake->direction = ch;
}
}
}
}
int main() {
Snake snake;
Food food;
initSnake(&snake);
initFood(&food);
drawMap();
generateFood(&food, &snake);
while (1) {
drawSnake(&snake);
drawFood(&food);
updateDirection(&snake);
updateSnake(&snake, &food);
Sleep(speed);
}
return ;
}
阅读全文