帮我用C语言写贪吃蛇代码
时间: 2023-06-01 18:05:40 浏览: 109
好的,我可以为您提供贪吃蛇的代码。以下是一个简单的贪吃蛇游戏的C源代码:
```c
#include <stdio.h>
#include <conio.h>
#include <windows.h>
#define ROWS 20
#define COLS 20
void gotoxy(int x, int y) {
COORD coord = { x, y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void drawBorder() {
int i, j;
for (i = 0; i < ROWS + 1; ++i) {
for (j = 0; j < COLS + 1; ++j) {
if (i == 0 || i == ROWS || j == 0 || j == COLS) {
gotoxy(i, j);
printf("+");
}
}
}
}
int main() {
int headX, headY;
char input;
int gameOver = 0;
int score = 0;
int tailX[100];
int tailY[100];
int tailLen = 0;
headX = ROWS / 2;
headY = COLS / 2;
while (1) {
gotoxy(0, 0);
printf("Score: %d\n", score);
drawBorder();
// Draw the snake's head
gotoxy(headX, headY);
printf("O");
// Record the previous position of the snake's head
tailX[tailLen] = headX;
tailY[tailLen] = headY;
tailLen++;
// Clear the last position of the snake's tail.
gotoxy(tailX[0], tailY[0]);
printf(" ");
tailLen--;
int i;
for (i = 0; i < tailLen; ++i) {
tailX[i] = tailX[i + 1];
tailY[i] = tailY[i + 1];
}
if (_kbhit()) {
input = _getch();
if (input == 'w') {
headX--;
}
else if (input == 'a') {
headY--;
}
else if (input == 's') {
headX++;
}
else if (input == 'd') {
headY++;
}
}
if (headX == 0 || headX == ROWS || headY == 0 || headY == COLS) {
gameOver = 1;
}
// Check if the snake's head intersects with its tail
for (i = 0; i < tailLen; ++i) {
if (headX == tailX[i] && headY == tailY[i]) {
gameOver = 1;
break;
}
}
if (gameOver) {
gotoxy(ROWS / 2 - 3, COLS / 2);
printf("Game Over");
break;
}
Sleep(100);
}
return 0;
}
```
这是一个基础的代码,您可以根据您的需求进行修改。
阅读全文