用C语言写一个贪吃蛇代码,包含所有代码
时间: 2023-12-29 22:15:25 浏览: 9
我很乐意为您编写一个贪吃蛇代码,包含所有代码。以下是代码:#include <stdio.h>
#include <stdlib.h>
#include <windows.h>int main()
{
// 初始化游戏
int i, j;
int score = 0;
int level = 1;
int speed = 200;
int food_x = 0;
int food_y = 0;
int size = 3;
int snake_x[60] = {0};
int snake_y[60] = {0};
int dir = 0; // 初始化屏幕
system("cls");
for (i = 0; i < 20; i++) {
for (j = 0; j < 30; j++) {
printf(" ");
}
printf("\n");
} // 初始化蛇的位置
snake_x[0] = 15;
snake_y[0] = 10;
for (i = 1; i < size; i++) {
snake_x[i] = snake_x[i - 1] - 1;
snake_y[i] = snake_y[i - 1];
} // 生成食物
food_x = rand() % 20;
food_y = rand() % 30; // 开始游戏
while (1) {
// 画出屏幕
system("cls");
for (i = 0; i < 20; i++) {
for (j = 0; j < 30; j++) {
if (i == 0 || i == 19 || j == 0 || j == 29) {
printf("*");
}
else {
int flag = 0;
for (int k = 0; k < size; k++) {
if (i == snake_x[k] && j == snake_y[k]) {
printf("@");
flag = 1;
break;
}
}
if (flag == 0) {
if (i == food_x && j == food_y) {
printf("$");
}
else {
printf(" ");
}
}
}
}
printf("\n");
} // 获取用户输入
if (kbhit()) {
char ch = getch();
if (ch == 'a' && dir != 2) {
dir = 1;
}
else if (ch == 'd' && dir != 1) {
dir = 2;
}
else if (ch == 'w' && dir != 4) {
dir = 3;
}
else if (ch == 's' && dir != 3) {
dir = 4;
}
} // 游戏逻辑
for (i = size - 1; i > 0; i--) {
snake_x[i] = snake_x[i - 1];
snake_y[i] = snake_y[i - 1];
}
switch (dir) {
case 1:
snake_y[0]--;
break;
case 2:
snake_y[0]++;
break;
case 3:
snake_x[0]--;
break;
case 4:
snake_x[0]++;
break;
} // 判断游戏是否结束
if (snake_x[0] == 0 || snake_x[0] == 19 || snake_y[0] == 0 || snake_y[0] == 29) {
printf("游戏结束,您的得分为:%d\n", score);
break;
}
for (i = 1; i < size; i++) {
if (snake_x[0] == snake_x[i] && snake_y[0] == snake_y[i]) {
printf("游戏结束,您的得分为:%d\n", score);
break;
}
} // 判断蛇是否吃到食物
if (snake_x[0] == food_x && snake_y[0] == food_y) {
size++;
food_x = rand() % 20;
food_y = rand() % 30;
score += 10;
if (score % 50 == 0) {
level++;
speed -= 50;
}
} Sleep(speed);
} return 0;
}
阅读全文