用c++写一个贪吃蛇游戏
时间: 2023-04-03 09:04:10 浏览: 59
好的,我可以回答这个问题。以下是一个简单的贪吃蛇游戏的 C 代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 20
#define HEIGHT 20
#define INIT_LENGTH 3
int x, y; // 蛇头的坐标
int fx, fy; // 食物的坐标
int length; // 蛇的长度
int score; // 得分
int speed; // 速度
int direction; // 方向
int bodyX[WIDTH * HEIGHT]; // 蛇身的横坐标
int bodyY[WIDTH * HEIGHT]; // 蛇身的纵坐标
void init(); // 初始化游戏
void draw(); // 绘制游戏界面
void update(); // 更新游戏状态
void generateFood(); // 生成食物
void gameOver(); // 游戏结束
int main() {
init();
while (1) {
draw();
update();
Sleep(1000 / speed);
}
return 0;
}
void init() {
x = WIDTH / 2;
y = HEIGHT / 2;
length = INIT_LENGTH;
score = 0;
speed = 5;
direction = 'w';
for (int i = 0; i < length; i++) {
bodyX[i] = x;
bodyY[i] = y + i;
}
generateFood();
}
void draw() {
system("cls");
for (int i = 0; i < WIDTH + 2; i++) {
printf("#");
}
printf("\n");
for (int i = 0; i < HEIGHT; i++) {
printf("#");
for (int j = 0; j < WIDTH; j++) {
if (i == y && j == x) {
printf("O");
} else if (i == fy && j == fx) {
printf("F");
} else {
int flag = 0;
for (int k = 0; k < length; k++) {
if (i == bodyY[k] && j == bodyX[k]) {
printf("o");
flag = 1;
break;
}
}
if (!flag) {
printf(" ");
}
}
}
printf("#\n");
}
for (int i = 0; i < WIDTH + 2; i++) {
printf("#");
}
printf("\n");
printf("Score: %d\n", score);
printf("Speed: %d\n", speed);
}
void update() {
if (_kbhit()) {
char ch = _getch();
if (ch == 'w' || ch == 'a' || ch == 's' || ch == 'd') {
if (abs(ch - direction) != 2) {
direction = ch;
}
}
}
int dx = 0, dy = 0;
switch (direction) {
case 'w':
dy = -1;
break;
case 'a':
dx = -1;
break;
case 's':
dy = 1;
break;
case 'd':
dx = 1;
break;
}
int newX = x + dx;
int newY = y + dy;
if (newX < 0 || newX >= WIDTH || newY < 0 || newY >= HEIGHT) {
gameOver();
return;
}
if (newX == fx && newY == fy) {
score++;
length++;
if (score % 5 == 0) {
speed++;
}
generateFood();
}
for (int i = length - 1; i > 0; i--) {
bodyX[i] = bodyX[i - 1];
bodyY[i] = bodyY[i - 1];
}
bodyX[0] = x;
bodyY[0] = y;
for (int i = 1; i < length; i++) {
if (newX == bodyX[i] && newY == bodyY[i]) {
gameOver();
return;
}
}
x = newX;
y = newY;
}
void generateFood() {
srand((unsigned)time(NULL));
fx = rand() % WIDTH;
fy = rand() % HEIGHT;
for (int i = 0; i < length; i++) {
if (fx == bodyX[i] && fy == bodyY[i]) {
generateFood();
return;
}
}
}
void gameOver() {
system("cls");
printf("Game Over!\n");
printf("Score: %d\n", score);
exit(0);
}
阅读全文