写一下贪吃蛇的C语言程序
时间: 2024-09-12 16:08:31 浏览: 35
贪吃蛇 C语言程序
5星 · 资源好评率100%
贪吃蛇是一款经典的电子游戏,玩家控制一条不断增长的蛇,通过吃掉屏幕上出现的食物来获得分数,同时避免蛇头撞到自己的身体或游戏边界。
以下是一个简化的贪吃蛇游戏的C语言程序的基本框架,由于编写完整的贪吃蛇程序相对复杂,这里只提供核心思路和部分代码片段,不包括完整的功能实现。
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 20
#define HEIGHT 20
int x, y, fruitX, fruitY, score;
int tailX[100], tailY[100];
int nTail;
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN};
enum eDirection dir;
void Setup() {
dir = STOP;
x = WIDTH / 2;
y = HEIGHT / 2;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
score = 0;
}
void Draw() {
system("cls");
for (int i = 0; i < WIDTH + 2; i++)
printf("#");
printf("\n");
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (j == 0)
printf("#");
if (i == y && j == x)
printf("O");
else if (i == fruitY && j == fruitX)
printf("F");
else {
int print = 0;
for (int k = 0; k < nTail; k++) {
if (tailX[k] == j && tailY[k] == i) {
printf("o");
print = 1;
}
}
if (!print)
printf(" ");
}
if (j == WIDTH - 1)
printf("#");
}
printf("\n");
}
for (int i = 0; i < WIDTH + 2; i++)
printf("#");
printf("\n");
printf("Score: %d\n", score);
}
void Input() {
if (_kbhit()) {
switch (_getch()) {
case 'a':
dir = LEFT;
break;
case 'd':
dir = RIGHT;
break;
case 'w':
dir = UP;
break;
case 's':
dir = DOWN;
break;
case 'x':
dir = STOP;
break;
}
}
}
void Logic() {
// Move the tail
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < nTail; i++) {
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
// Move the snake's head
switch (dir) {
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
default:
break;
}
// Check collision with the walls
if (x >= WIDTH || x < 0 || y >= HEIGHT || y < 0)
dir = STOP; // Game over
// Check collision with the tail
for (int i = 0; i < nTail; i++)
if (tailX[i] == x && tailY[i] == y)
dir = STOP; // Game over
// Check if snake has eaten the fruit
if (x == fruitX && y == fruitY) {
score += 10;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
nTail++;
}
}
int main() {
Setup();
while (dir != STOP) {
Draw();
Input();
Logic();
Sleep(100); // Sleep for 100 milliseconds
}
return 0;
}
```
这个程序实现了贪吃蛇游戏的基本框架,包括游戏初始化、绘制游戏界面、处理输入和游戏逻辑。注意,这个程序需要在支持conio.h和windows.h的环境中编译和运行,例如Windows的命令提示符或者使用支持这些库的编译器。
阅读全文