用c语言写个贪吃蛇代码
时间: 2023-03-31 15:04:48 浏览: 76
贪吃蛇c语言代码
我可以回答这个问题。以下是一个简单的贪吃蛇游戏的 C 语言代码:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#define WIDTH 20
#define HEIGHT 20
#define SNAKE_MAX_LENGTH 100
int snakeX[SNAKE_MAX_LENGTH], snakeY[SNAKE_MAX_LENGTH];
int snakeLength = 3;
int foodX, foodY;
int direction = ; // : up, 1: right, 2: down, 3: left
void initSnake() {
snakeX[] = WIDTH / 2;
snakeY[] = HEIGHT / 2;
for (int i = 1; i < snakeLength; i++) {
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1] + 1;
}
}
void generateFood() {
srand(time(NULL));
foodX = rand() % WIDTH;
foodY = rand() % HEIGHT;
}
void draw() {
system("cls");
for (int i = ; i < WIDTH + 2; i++) {
printf("#");
}
printf("\n");
for (int i = ; i < HEIGHT; i++) {
printf("#");
for (int j = ; j < WIDTH; j++) {
if (i == snakeY[] && j == snakeX[]) {
printf("O");
} else if (i == foodY && j == foodX) {
printf("F");
} else {
int isBodyPart = ;
for (int k = 1; k < snakeLength; k++) {
if (i == snakeY[k] && j == snakeX[k]) {
printf("o");
isBodyPart = 1;
break;
}
}
if (!isBodyPart) {
printf(" ");
}
}
}
printf("#\n");
}
for (int i = ; i < WIDTH + 2; i++) {
printf("#");
}
printf("\n");
}
void update() {
int oldX = snakeX[];
int oldY = snakeY[];
switch (direction) {
case :
snakeY[]--;
break;
case 1:
snakeX[]++;
break;
case 2:
snakeY[]++;
break;
case 3:
snakeX[]--;
break;
}
if (snakeX[] == foodX && snakeY[] == foodY) {
snakeLength++;
generateFood();
}
for (int i = 1; i < snakeLength; i++) {
int tempX = snakeX[i];
int tempY = snakeY[i];
snakeX[i] = oldX;
snakeY[i] = oldY;
oldX = tempX;
oldY = tempY;
}
if (snakeX[] < || snakeX[] >= WIDTH || snakeY[] < || snakeY[] >= HEIGHT) {
printf("Game over!\n");
exit();
}
for (int i = 1; i < snakeLength; i++) {
if (snakeX[] == snakeX[i] && snakeY[] == snakeY[i]) {
printf("Game over!\n");
exit();
}
}
}
int main() {
initSnake();
generateFood();
while (1) {
draw();
update();
if (_kbhit()) {
switch (_getch()) {
case 'w':
if (direction != 2) {
direction = ;
}
break;
case 'd':
if (direction != 3) {
direction = 1;
}
break;
case 's':
if (direction != ) {
direction = 2;
}
break;
case 'a':
if (direction != 1) {
direction = 3;
}
break;
}
}
Sleep(100);
}
return ;
}
阅读全文