使用c语言编写一个贪吃蛇游戏
时间: 2024-05-05 07:21:48 浏览: 99
好的,下面是一个简单的贪吃蛇游戏的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define width 40
#define height 20
int x, y, foodX, foodY, score, gameover;
int tailX[100], tailY[100];
int ntail = 0;
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
enum eDirection dir;
void Setup() {
gameover = 0;
dir = STOP;
x = width / 2;
y = height / 2;
foodX = rand() % width;
foodY = 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 == foodY && j == foodX)
printf("F");
else {
int printTail = 0;
for (int k = 0; k < ntail; k++) {
if (tailX[k] == j && tailY[k] == i) {
printf("o");
printTail = 1;
}
}
if (!printTail)
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':
gameover = 1;
break;
}
}
}
void Logic() {
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;
}
switch (dir) {
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
default:
break;
}
if (x >= width) x = 0; else if (x < 0) x = width - 1;
if (y >= height) y = 0; else if (y < 0) y = height - 1;
for (int i = 0; i < ntail; i++)
if (tailX[i] == x && tailY[i] == y)
gameover = 1;
if (x == foodX && y == foodY) {
score += 10;
foodX = rand() % width;
foodY = rand() % height;
ntail++;
}
}
int main() {
Setup();
while (!gameover) {
Draw();
Input();
Logic();
Sleep(50);
}
return 0;
}
```
这个游戏使用了Windows.h头文件中的Sleep函数,需要在Windows系统下运行。游戏运行后,使用wasd控制方向,x键退出游戏。
阅读全文