贪吃蛇游戏c语言代码
时间: 2023-10-23 09:11:41 浏览: 112
贪吃蛇游戏c语言源代码.doc
这是一个简单的贪吃蛇游戏的C语言代码。游戏中包括了蛇的初始化、食物的初始化、控制台光标位置的修改、蛇的移动控制等功能。你可以根据需要对代码进行修改和完善。
代码如下:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define WIDE 60
#define HIGH 30
typedef struct {
int X;
int Y;
} Point;
typedef struct {
Point body[100];
int size;
} Snake;
Point food;
Snake snake;
int kx = 1, ky = 0;
void initSnake(void) {
snake.size = 2;
snake.body[0].X = WIDE/2;
snake.body[0].Y = HIGH/2;
snake.body[1].X = WIDE/2 - 1;
snake.body[1].Y = HIGH/2;
}
void initFood(void) {
food.X = rand() % WIDE;
food.Y = rand() % HIGH;
}
void initUI(void) {
COORD coord = {0};
for (int i = 0; i < snake.size; i++) {
coord.X = snake.body[i].X;
coord.Y = snake.body[i].Y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
if (i == 0) putchar('@');
else putchar('*');
}
coord.X = food.X;
coord.Y = food.Y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
putchar('#');
}
void playGame(void) {
char key = 'd';
while (1) {
if (kbhit()) {
key = getch();
switch (key) {
case 'a': kx = -1; ky = 0; break;
case 'd': kx = 1; ky = 0; break;
case 'w': kx = 0; ky = -1; break;
case 's': kx = 0; ky = 1; break;
}
}
Point tail = snake.body[snake.size - 1];
for (int i = snake.size - 1; i > 0; i--) {
snake.body[i] = snake.body[i - 1];
}
snake.body[0].X += kx;
snake.body[0].Y += ky;
if (snake.body[0].X < 0 || snake.body[0].X >= WIDE || snake.body[0].Y < 0 || snake.body[0].Y >= HIGH) {
printf("Game Over!\n");
break;
}
for (int i = 1; i < snake.size; i++) {
if (snake.body[0].X == snake.body[i].X && snake.body[0].Y == snake.body[i].Y) {
printf("Game Over!\n");
return;
}
}
if (snake.body[0].X == food.X && snake.body[0].Y == food.Y) {
snake.body[snake.size++] = tail;
initFood();
}
system("cls");
initUI();
Sleep(100);
}
}
int main(void) {
initSnake();
initFood();
initUI();
playGame();
return 0;
}
```
阅读全文