帮我用c语言写个贪吃蛇
时间: 2023-06-08 20:03:58 浏览: 94
好的,我会根据您的要求使用 C 语言来编写贪吃蛇游戏。以下是代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
// 定义常量
#define WIDTH 30
#define HEIGHT 20
#define MAX_LEN (WIDTH - 2) * (HEIGHT - 2)
// 定义蛇的结构体
struct Snake{
int x;
int y;
};
// 初始化蛇
void init_snake(struct Snake s[], int len){
int i;
for(i = 0; i < len; i++){
s[i].x = WIDTH / 2 + 1 - i;
s[i].y = HEIGHT / 2;
}
}
// 画出边框
void draw_border(){
int i, j;
for(i = 0; i <= HEIGHT; i++){
for(j = 0; j <= WIDTH; j++){
if(i == 0 || i == HEIGHT || j == 0 || j == WIDTH){
printf("#");
}
else{
printf(" ");
}
}
printf("\n");
}
}
// 画出蛇
void draw_snake(struct Snake s[], int len){
int i;
for(i = 0; i < len; i++){
printf("O");
gotoxy(s[i].x, s[i].y);
}
}
// 生成食物
void generate_food(int *food_x, int *food_y){
srand((unsigned)time(NULL));
*food_x = rand() % (WIDTH - 2) + 1;
*food_y = rand() % (HEIGHT - 2) + 1;
}
// 判断是否吃到食物
int eat_food(struct Snake s[], int len, int food_x, int food_y){
if(s[0].x == food_x && s[0].y == food_y){
len++;
s[len-1].x = s[len-2].x;
s[len-1].y = s[len-2].y;
return 1;
}
return 0;
}
// 判断是否撞到自己
int hit_self(struct Snake s[], int len){
int i;
for(i = 1; i < len; i++){
if(s[0].x == s[i].x && s[0].y == s[i].y){
return 1;
}
}
return 0;
}
// 判断是否撞墙
int hit_wall(struct Snake s[]){
if(s[0].x == 0 || s[0].x == WIDTH || s[0].y == 0 || s[0].y == HEIGHT){
return 1;
}
return 0;
}
// 控制蛇的移动
void move(struct Snake s[], int len, int food_x, int food_y){
int i;
int key;
int old_x, old_y;
while(1){
old_x = s[len-1].x;
old_y = s[len-1].y;
for(i = len-1; i > 0; i--){
s[i].x = s[i-1].x;
s[i].y = s[i-1].y;
}
key = getch();
switch(key){
case 72: // 上
s[0].y--;
break;
case 80: // 下
s[0].y++;
break;
case 75: // 左
s[0].x--;
break;
case 77: // 右
s[0].x++;
break;
default:
break;
}
if(hit_wall(s) || hit_self(s, len)){
printf("Game Over!\n");
break;
}
if(eat_food(s, len, food_x, food_y)){
len++;
generate_food(&food_x, &food_y);
}
system("cls");
draw_border();
printf("Score: %d\n", len-3);
gotoxy(food_x, food_y);
printf("$");
draw_snake(s, len);
Sleep(200);
}
}
int main(){
int food_x, food_y;
struct Snake s[MAX_LEN];
int len = 3;
draw_border();
init_snake(s, len);
generate_food(&food_x, &food_y);
gotoxy(food_x, food_y);
printf("$");
draw_snake(s, len);
printf("Score: 0\n");
move(s, len, food_x, food_y);
return 0;
}
```
希望这个代码能够满足您的需求。如果您还有其他问题或需求,欢迎继续咨询我。
阅读全文