用dev-c++编写贪吃蛇的代码
时间: 2024-01-14 07:41:53 浏览: 195
DevC++贪吃蛇小游戏
以下是使用Dev-C++编写的贪吃蛇代码,仅供参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <time.h>
#define MAX_X 20
#define MAX_Y 20
int foodX, foodY;
int snakeX[100], snakeY[100];
int snakeLen = 4;
int dir = 0; // 0-上,1-右,2-下,3-左
int score = 0;
// 初始化蛇和食物位置
void init() {
snakeX[0] = 5;
snakeY[0] = 5;
snakeX[1] = 5;
snakeY[1] = 6;
snakeX[2] = 5;
snakeY[2] = 7;
snakeX[3] = 5;
snakeY[3] = 8;
snakeLen = 4;
dir = 0;
srand((unsigned)time(NULL));
foodX = rand() % MAX_X + 1;
foodY = rand() % MAX_Y + 1;
score = 0;
}
// 显示游戏界面
void show() {
system("cls");
for (int i = 0; i <= MAX_X + 1; i++) {
printf("#");
}
printf("\n");
for (int i = 1; i <= MAX_Y; i++) {
printf("#");
for (int j = 1; j <= MAX_X; j++) {
if (i == foodY && j == foodX) {
printf("F");
} else {
int flag = 0;
for (int k = 0; k < snakeLen; k++) {
if (i == snakeY[k] && j == snakeX[k]) {
printf("O");
flag = 1;
break;
}
}
if (flag == 0) {
printf(" ");
}
}
}
printf("#\n");
}
for (int i = 0; i <= MAX_X + 1; i++) {
printf("#");
}
printf("\n");
printf("Score: %d\n", score);
}
// 移动蛇
void move() {
int tailX = snakeX[snakeLen - 1];
int tailY = snakeY[snakeLen - 1];
for (int i = snakeLen - 1; i > 0; i--) {
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
if (dir == 0) {
snakeY[0]--;
} else if (dir == 1) {
snakeX[0]++;
} else if (dir == 2) {
snakeY[0]++;
} else if (dir == 3) {
snakeX[0]--;
}
if (snakeX[0] == foodX && snakeY[0] == foodY) {
snakeX[snakeLen] = tailX;
snakeY[snakeLen] = tailY;
snakeLen++;
score++;
foodX = rand() % MAX_X + 1;
foodY = rand() % MAX_Y + 1;
}
}
// 判断游戏是否结束
int isGameOver() {
if (snakeX[0] <= 0 || snakeX[0] > MAX_X || snakeY[0] <= 0 || snakeY[0] > MAX_Y) {
return 1;
}
for (int i = 1; i < snakeLen; i++) {
if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
return 1;
}
}
return 0;
}
int main() {
init();
while (1) {
show();
move();
if (isGameOver()) {
printf("Game Over!\n");
break;
}
Sleep(200);
if (_kbhit()) {
int ch = _getch();
if (ch == 'w' || ch == 'W') {
if (dir != 2) {
dir = 0;
}
} else if (ch == 'd' || ch == 'D') {
if (dir != 3) {
dir = 1;
}
} else if (ch == 's' || ch == 'S') {
if (dir != 0) {
dir = 2;
}
} else if (ch == 'a' || ch == 'A') {
if (dir != 1) {
dir = 3;
}
}
}
}
return 0;
}
```
该程序使用了Windows API函数`Sleep()`和`_kbhit()`,需要在`<windows.h>`头文件中声明。`Sleep()`函数可以让程序暂停一段时间,这里用于控制蛇的移动速度;`_kbhit()`函数用于检测键盘是否有输入,如果有则获取键盘输入并修改蛇的移动方向。
阅读全文