请帮我用c语言写个贪吃蛇代码
时间: 2023-03-28 21:04:36 浏览: 70
好的,以下是贪吃蛇的 C 语言代码:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define MAX_X 20
#define MAX_Y 20
#define INIT_LEN 3
int x, y, len, score, speed;
int food_x, food_y;
int body_x[MAX_X * MAX_Y], body_y[MAX_X * MAX_Y];
int direction_x[4] = {, , -1, 1};
int direction_y[4] = {-1, 1, , };
void init();
void draw();
void update();
void generate_food();
void game_over();
int main() {
init();
while (1) {
draw();
update();
Sleep(speed);
}
return ;
}
void init() {
x = MAX_X / 2;
y = MAX_Y / 2;
len = INIT_LEN;
score = ;
speed = 200;
for (int i = ; i < len; i++) {
body_x[i] = x;
body_y[i] = y + i;
}
generate_food();
}
void draw() {
system("cls");
for (int i = ; i < MAX_X; i++) {
for (int j = ; j < MAX_Y; j++) {
if (i == x && j == y) {
printf("O");
} else if (i == food_x && j == food_y) {
printf("*");
} else {
int flag = ;
for (int k = ; k < len; k++) {
if (i == body_x[k] && j == body_y[k]) {
printf("o");
flag = 1;
break;
}
}
if (!flag) {
printf(" ");
}
}
}
printf("\n");
}
printf("Score: %d\n", score);
}
void update() {
int next_x = x + direction_x[_getch() - ''];
int next_y = y + direction_y[_getch() - ''];
if (next_x < || next_x >= MAX_X || next_y < || next_y >= MAX_Y) {
game_over();
return;
}
if (next_x == food_x && next_y == food_y) {
len++;
score += 10;
if (score % 50 == ) {
speed -= 20;
}
generate_food();
}
for (int i = len - 1; i > ; i--) {
body_x[i] = body_x[i - 1];
body_y[i] = body_y[i - 1];
}
body_x[] = x;
body_y[] = y;
x = next_x;
y = next_y;
for (int i = 1; i < len; i++) {
if (x == body_x[i] && y == body_y[i]) {
game_over();
return;
}
}
}
void generate_food() {
int flag = ;
while (!flag) {
food_x = rand() % MAX_X;
food_y = rand() % MAX_Y;
flag = 1;
for (int i = ; i < len; i++) {
if (food_x == body_x[i] && food_y == body_y[i]) {
flag = ;
break;
}
}
}
}
void game_over() {
system("cls");
printf("Game over!\n");
printf("Your score is: %d\n", score);
exit();
}
阅读全文