编写一个c语言贪吃蛇游戏的代码
时间: 2023-05-31 07:07:50 浏览: 135
好的,我可以为您提供贪吃蛇游戏的C语言代码。以下是代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#include <Windows.h>
#define WIDTH 50
#define HEIGHT 20
int score = 0;
int speed = 200;
int food_x, food_y;
int snake_size = 3;
int snake_x[100] = { 25,25,25 }, snake_y[100] = { 10,9,8 };
int dir = 2;
void gotoxy(int x, int y) {
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
void draw_wall() {
for (int i = 0; i < WIDTH; i++) {
gotoxy(i, 0); printf("#");
gotoxy(i, HEIGHT); printf("#");
}
for (int i = 0; i < HEIGHT; i++) {
gotoxy(0, i); printf("#");
gotoxy(WIDTH, i); printf("#");
}
}
void update_score() {
gotoxy(WIDTH + 5, 5); printf("Score: %d", score);
gotoxy(WIDTH + 5, 6); printf("Speed: %d", speed);
}
void generate_food() {
int flag = 1;
while (flag) {
flag = 0;
food_x = rand() % (WIDTH - 2) + 1;
food_y = rand() % (HEIGHT - 2) + 1;
for (int i = 0; i < snake_size; i++)
if (snake_x[i] == food_x && snake_y[i] == food_y) flag = 1;
}
gotoxy(food_x, food_y); printf("$");
}
void update_snake() {
gotoxy(snake_x[snake_size - 1], snake_y[snake_size - 1]); printf(" ");
for (int i = snake_size - 1; i >= 1; i--) {
snake_x[i] = snake_x[i - 1];
snake_y[i] = snake_y[i - 1];
}
if (dir == 0) snake_y[0]--;
if (dir == 1) snake_x[0]++;
if (dir == 2) snake_y[0]++;
if (dir == 3) snake_x[0]--;
gotoxy(snake_x[0], snake_y[0]); printf("#");
}
void game_over() {
system("cls");
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\t\tGame Over!\n\n\t\t\t\tYour score is %d\n\n", score);
system("pause");
exit(0);
}
int main() {
srand((unsigned int)time(NULL));
draw_wall();
generate_food();
update_score();
while (1) {
if (_kbhit()) {
char ch = _getch();
if (ch == 'w' && dir != 2) dir = 0;
if (ch == 'd' && dir != 3) dir = 1;
if (ch == 's' && dir != 0) dir = 2;
if (ch == 'a' && dir != 1) dir = 3;
}
if (snake_x[0] == 0 || snake_x[0] == WIDTH || snake_y[0] == 0 || snake_y[0] == HEIGHT) game_over();
for (int i = 1; i < snake_size; i++)
if (snake_x[i] == snake_x[0] && snake_y[i] == snake_y[0]) game_over();
if (snake_x[0] == food_x && snake_y[0] == food_y) {
snake_size++;
score += 10;
speed -= 5;
generate_food();
update_score();
}
update_snake();
Sleep(speed);
}
return 0;
}
```
这个程序是一个控制台应用程序,使用了Windows API函数来实现控制光标移动、生成随机数等功能。玩家可以通过控制台窗口输入"w"、"a"、"s"、"d"来控制蛇前进的方向,吃到食物可以获得分数,随着分数的增加蛇的速度会越来越快。但是如果蛇碰到墙壁或者自己,游戏就会结束。
阅读全文