写一个贪吃蛇游戏c语言代码
时间: 2023-04-08 11:03:11 浏览: 138
我可以回答这个问题。以下是一个简单的贪吃蛇游戏的C语言代码:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 20
#define HEIGHT 20
int score = 0;
int gameover = 0;
int speed = 100;
COORD snake[100];
COORD food;
enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN };
enum Direction dir;
void Setup() {
gameover = 0;
dir = STOP;
snake[0].X = WIDTH / 2;
snake[0].Y = HEIGHT / 2;
food.X = rand() % WIDTH;
food.Y = rand() % HEIGHT;
score = 0;
}
void Draw() {
system("cls");
for (int i = 0; i < WIDTH + 2; i++)
printf("#");
printf("\n");
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (j == 0)
printf("#");
if (i == snake[0].Y && j == snake[0].X)
printf("O");
else if (i == food.Y && j == food.X)
printf("F");
else {
int print = 0;
for (int k = 1; k < score; k++) {
if (snake[k].X == j && snake[k].Y == i) {
printf("o");
print = 1;
}
}
if (!print)
printf(" ");
}
if (j == WIDTH - 1)
printf("#");
}
printf("\n");
}
for (int i = 0; i < WIDTH + 2; i++)
printf("#");
printf("\n");
printf("Score: %d\n", score);
}
void Input() {
if (_kbhit()) {
switch (_getch()) {
case 'a':
dir = LEFT;
break;
case 'd':
dir = RIGHT;
break;
case 'w':
dir = UP;
break;
case 's':
dir = DOWN;
break;
case 'x':
gameover = 1;
break;
}
}
}
void Logic() {
COORD prev = snake[0];
COORD prev2;
snake[0] = food;
for (int i = 1; i < score; i++) {
prev2 = snake[i];
snake[i] = prev;
prev = prev2;
}
switch (dir) {
case LEFT:
snake[0].X--;
break;
case RIGHT:
snake[0].X++;
break;
case UP:
snake[0].Y--;
break;
case DOWN:
snake[0].Y++;
break;
}
if (snake[0].X == food.X && snake[0].Y == food.Y) {
score++;
food.X = rand() % WIDTH;
food.Y = rand() % HEIGHT;
}
if (snake[0].X < 0 || snake[0].X >= WIDTH || snake[0].Y < 0 || snake[0].Y >= HEIGHT)
gameover = 1;
for (int i = 1; i < score; i++) {
if (snake[0].X == snake[i].X && snake[0].Y == snake[i].Y)
gameover = 1;
}
}
int main() {
Setup();
while (!gameover) {
Draw();
Input();
Logic();
Sleep(speed);
}
printf("Game Over!\n");
return 0;
}
阅读全文