写个贪吃蛇的C#代码
时间: 2023-03-02 08:27:46 浏览: 103
贪吃蛇C#代码
好的,以下是一个简单的贪吃蛇的C语言代码示例:
```
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#define WIDTH 50 // 地图宽度
#define HEIGHT 20 // 地图高度
int snake[100][2]; // 存储蛇身的坐标
int length = 3; // 蛇的初始长度
int direction; // 蛇的移动方向
int food_x, food_y; // 食物的坐标
// 初始化游戏
void init_game() {
// 初始化蛇的位置
int x = WIDTH / 2, y = HEIGHT / 2;
snake[0][0] = x;
snake[0][1] = y;
for (int i = 1; i < length; i++) {
snake[i][0] = x - i;
snake[i][1] = y;
}
// 随机放置食物
srand(time(NULL));
food_x = rand() % WIDTH;
food_y = rand() % HEIGHT;
}
// 游戏主循环
void game_loop() {
while (1) {
// 画出地图和蛇
system("cls");
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
int is_snake = 0;
for (int i = 0; i < length; i++) {
if (snake[i][0] == x && snake[i][1] == y) {
is_snake = 1;
break;
}
}
if (is_snake) {
printf("*");
} else if (x == food_x && y == food_y) {
printf("#");
} else {
printf(" ");
}
}
printf("\n");
}
// 处理按键输入
if (_kbhit()) {
char ch = _getch();
if (ch == 'w') {
direction = 0;
} else if (ch == 'd') {
direction = 1;
} else if (ch == 's') {
direction = 2;
} else if (ch == 'a') {
direction = 3;
}
}
// 移动蛇
int head_x = snake[0][0], head_y = snake[0][1];
if (direction == 0) {
head_y--;
} else if (direction == 1) {
head_x++;
} else if (direction == 2) {
head_y++;
} else if (direction == 3) {
head_x--;
}
// 判断游戏是否结束
if (head_x < 0 || head_x >= WIDTH || head_y < 0 || head_y >= HEIGHT) {
printf("Game Over!\n");
break;
}
for (int i = 1; i < length; i++) {
if (snake[i][0] == head_x && snake[i][1] == head_y) {
printf("Game Over!\n");
goto end;
}
}
if (head_x == food_x && head_y == food_y) {
length++;
food_x = rand() % WIDTH;
阅读全文