贪吃蛇c语言程序代码简化版
时间: 2024-05-06 22:14:13 浏览: 177
贪吃蛇代码,c语言版
贪吃蛇是一个经典的小游戏,其实现需要使用图形界面或者游戏引擎。如果您希望了解C语言实现的简化版贪吃蛇,可以参考下面的代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 20 // 地图宽度
#define HEIGHT 20 // 地图高度
#define MAX_LENGTH (WIDTH * HEIGHT) // 蛇的最大长度
int snakeX[MAX_LENGTH]; // 蛇的x坐标
int snakeY[MAX_LENGTH]; // 蛇的y坐标
int length = 3; // 蛇的初始长度
int foodX, foodY; // 食物的坐标
int score = 0; // 得分
int direction; // 蛇头的方向:1为上,2为下,3为左,4为右
int speed = 200; // 蛇的速度
void initMap(); // 初始化地图
void initSnake(); // 初始化蛇
void generateFood(); // 生成食物
void move(); // 移动蛇
void updateDirection(); // 更新方向
void gameOver(); // 游戏结束
int main() {
initMap();
initSnake();
generateFood();
while (1) {
move();
Sleep(speed);
}
return 0;
}
void initMap() {
system("cls");
for (int i = 0; i < WIDTH + 2; i++) {
printf("#");
}
printf("\n");
for (int i = 0; i < HEIGHT; i++) {
printf("#");
for (int j = 0; j < WIDTH; j++) {
printf(" ");
}
printf("#\n");
}
for (int i = 0; i < WIDTH + 2; i++) {
printf("#");
}
printf("\n");
printf("Score: %d\n", score);
}
void initSnake() {
snakeX = WIDTH / 2;
snakeY = HEIGHT / 2;
snakeX = snakeX;
snakeY = snakeY + 1;
snakeX = snakeX;
snakeY = snakeY + 1;
for (int i = 0; i < length; i++) {
printf("@");
gotoxy(snakeX[i] + 1, snakeY[i] + 1);
}
}
void generateFood() {
srand((unsigned)time(NULL));
do {
foodX = rand() % WIDTH;
foodY = rand() % HEIGHT;
} while (foodX == snakeX && foodY == snakeY);
gotoxy(foodX + 1, foodY + 1);
printf("*");
}
void move() {
if (_kbhit()) {
updateDirection();
}
int tailX = snakeX[length - 1];
int tailY = snakeY[length - 1];
gotoxy(tailX + 1, tailY + 1);
printf(" ");
for (int i = length - 1; i > 0; i--) {
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
switch (direction) {
case 1:
snakeY--;
break;
case 2:
snakeY++;
break;
case 3:
snakeX--;
break;
case 4:
snakeX++;
break;
}
if (snakeX == foodX && snakeY == foodY) {
score++;
length++;
generateFood();
if (speed > 50) {
speed -= 10;
}
}
if (snakeX < 0 || snakeX >= WIDTH || snakeY < 0 || snakeY >= HEIGHT) {
gameOver();
return;
}
for (int i = 1; i < length; i++) {
if (snakeX[i] == snakeX && snakeY[i] == snakeY) {
gameOver();
return;
}
}
gotoxy(snakeX[0] + 1, snakeY + 1);
printf("@");
gotoxy(WIDTH + 4, 2);
printf("Score: %d", score);
}
void updateDirection() {
char ch = _getch();
switch (ch) {
case 'w':
if (direction != 2) {
direction = 1;
}
break;
case 's':
if (direction != 1) {
direction = 2;
}
break;
case 'a':
if (direction != 4) {
direction = 3;
}
break;
case 'd':
if (direction != 3) {
direction = 4;
}
break;
}
}
void gameOver() {
system("cls");
printf("Game Over!\n");
printf("Score: %d\n", score);
system("pause");
exit(0);
}
```
以上是简化版贪吃蛇的C语言代码。在这个代码中,我们使用了Windows API中的`gotoxy()`函数,来实现在控制台上输出蛇和食物。
阅读全文