给我生成一个c语言实现贪吃蛇的代码
由于贪吃蛇游戏的实现涉及到很多细节,因此这里只提供一个基本框架,供您参考:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 20 // 游戏界面宽度
#define HEIGHT 20 // 游戏界面高度
int score = 0; // 得分
int speed = 200; // 初始速度
typedef struct _position { // 坐标结构体
int x;
int y;
} POSITION;
POSITION head; // 蛇头
POSITION tail; // 蛇尾
POSITION food; // 食物
int direction; // 移动方向,0上1下2左3右
int map[WIDTH][HEIGHT]; // 地图,0空地1蛇身2食物
void init(); // 初始化
void draw(); // 绘制界面
void update(); // 更新游戏状态
void move(); // 移动蛇
void generateFood(); // 生成食物
void gameOver(); // 游戏结束
int main() {
init();
while (1) {
draw();
update();
Sleep(speed);
}
return 0;
}
void init() {
// 初始化地图
for (int i = 0; i < WIDTH; i++) {
for (int j = 0; j < HEIGHT; j++) {
map[i][j] = 0;
}
}
// 初始化蛇身
head.x = WIDTH / 2;
head.y = HEIGHT / 2;
tail = head;
map[head.x][head.y] = 1;
// 初始化方向
direction = 3;
// 生成食物
generateFood();
}
void draw() {
// 清屏
system("cls");
// 绘制地图
for (int i = 0; i < WIDTH; i++) {
for (int j = 0; j < HEIGHT; j++) {
if (map[i][j] == 0) {
printf(" ");
}
else if (map[i][j] == 1) {
printf("*");
}
else if (map[i][j] == 2) {
printf("#");
}
}
printf("\n");
}
// 绘制得分和速度
printf("Score: %d Speed: %d", score, speed);
}
void update() {
// 移动蛇
move();
// 判断是否吃到食物
if (head.x == food.x && head.y == food.y) {
score++;
generateFood();
speed -= 10;
}
// 判断是否撞墙或撞到自己
if (head.x < 0 || head.x >= WIDTH || head.y < 0 || head.y >= HEIGHT || map[head.x][head.y] == 1) {
gameOver();
}
}
void move() {
// 计算下一个位置
POSITION next;
if (direction == 0) {
next.x = head.x;
next.y = head.y - 1;
}
else if (direction == 1) {
next.x = head.x;
next.y = head.y + 1;
}
else if (direction == 2) {
next.x = head.x - 1;
next.y = head.y;
}
else if (direction == 3) {
next.x = head.x + 1;
next.y = head.y;
}
// 移动蛇头
map[head.x][head.y] = 1;
head = next;
// 判断是否吃到食物
if (head.x == food.x && head.y == food.y) {
map[head.x][head.y] = 1;
return;
}
// 移动蛇尾
map[tail.x][tail.y] = 0;
tail = (POSITION) { tail.x + (head.x - tail.x) / abs(head.x - tail.x), tail.y + (head.y - tail.y) / abs(head.y - tail.y) };
}
void generateFood() {
// 随机生成食物
do {
food.x = rand() % WIDTH;
food.y = rand() % HEIGHT;
} while (map[food.x][food.y] != 0);
map[food.x][food.y] = 2;
}
void gameOver() {
// 游戏结束
printf("\nGame Over!\n");
printf("Your score: %d\n", score);
system("pause");
exit(0);
}
这是一个简单的贪吃蛇游戏实现,您可以根据自己的需求进行修改和完善。
原文地址: https://www.cveoy.top/t/topic/bRO9 著作权归作者所有。请勿转载和采集!