C语言贪吃蛇代码代码简短实现
时间: 2023-10-03 22:05:54 浏览: 111
以下是一个简短实现的C语言贪吃蛇代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 40
#define HEIGHT 20
int x, y, fx, fy, score;
int snake[WIDTH * HEIGHT][2];
int len = 1;
void initSnake() {
x = WIDTH / 2;
y = HEIGHT / 2;
snake[0][0] = x;
snake[0][1] = y;
}
void initFood() {
srand(time(NULL));
fx = rand() % WIDTH;
fy = rand() % HEIGHT;
}
void draw() {
system("cls");
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (i == 0 || i == HEIGHT - 1 || j == 0 || j == WIDTH - 1)
printf("#");
else if (i == y && j == x)
printf("O");
else if (i == fy && j == fx)
printf("@");
else {
int flag = 0;
for (int k = 0; k < len; k++) {
if (snake[k][0] == j && snake[k][1] == i) {
printf("o");
flag = 1;
break;
}
}
if (!flag)
printf(" ");
}
}
printf("\n");
}
printf("Score: %d\n", score);
}
void move() {
int rx = x, ry = y;
if (_kbhit()) {
switch (_getch()) {
case 'w': y--; break;
case 'a': x--; break;
case 's': y++; break;
case 'd': x++; break;
}
}
if (x == fx && y == fy) {
len++;
score += 10;
initFood();
}
for (int i = 0; i < len; i++) {
int tempx = snake[i][0], tempy = snake[i][1];
snake[i][0] = rx;
snake[i][1] = ry;
rx = tempx;
ry = tempy;
}
}
int main() {
initSnake();
initFood();
while (1) {
draw();
move();
if (x < 1 || x >= WIDTH - 1 || y < 1 || y >= HEIGHT - 1) {
printf("Game Over\n");
break;
}
for (int i = 1; i < len; i++) {
if (x == snake[i][0] && y == snake[i][1]) {
printf("Game Over\n");
goto end;
}
}
Sleep(200);
}
end:
return 0;
}
```
希望对你有所帮助!
阅读全文