帮我写一个贪吃蛇的代码,用C++结构化编程
时间: 2023-02-25 21:36:28 浏览: 88
C++ 贪吃蛇的代码
好的,下面是一个简单的贪吃蛇游戏代码,使用 C 语言结构化编程实现:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define HEIGHT 20
#define WIDTH 40
#define SNAKE_LENGTH 5
int x[100], y[100]; // 蛇的每个部分的位置
int food_x, food_y; // 食物的位置
int direction = 1; // 蛇头的运动方向:1-右,2-下,3-左,4-上
int length = SNAKE_LENGTH; // 当前蛇的长度
void setCursor(int x, int y) {
COORD coord = {x, y};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void gotoxy(int x, int y) {
setCursor(x * 2, y);
}
void draw_food() {
gotoxy(food_x, food_y);
printf("F");
}
void draw_snake() {
int i;
for (i = 0; i < length; i++) {
gotoxy(x[i], y[i]);
printf("O");
}
}
void clear_screen() {
int i, j;
for (i = 0; i < HEIGHT; i++) {
for (j = 0; j < WIDTH; j++) {
gotoxy(j, i);
printf(" ");
}
}
}
void init_snake() {
int i;
for (i = 0; i < SNAKE_LENGTH; i++) {
x[i] = SNAKE_LENGTH - i;
y[i] = 0;
}
food_x = rand() % WIDTH;
food_y = rand() % HEIGHT;
}
void update_snake() {
int i;
for (i = length - 1; i > 0; i--) {
x[i] = x[i - 1];
y[i] = y[i - 1];
}
switch (direction) {
case 1:
x[0]++;
break;
case 2:
y[0]++;
break;
case 3:
x[0]--;
break;
case 4:
y[0]--;
break;
}
if (x[0] == food_x && y[0] == food_y) {
length++;
food_x = rand() % WIDTH;
food
阅读全文