用C++写一个贪吃蛇小游戏
时间: 2023-05-17 11:02:40 浏览: 147
非常感谢您的提问!以下是一个简单的贪吃蛇小游戏的C代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 30
#define HEIGHT 20
int score = 0;
int gameover = 0;
int speed = 100;
COORD snake[100];
int len = 3;
int dir = 3; // 1-up, 2-down, 3-left, 4-right
void gotoxy(int x, int y) {
COORD pos = {x, y};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
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 == snake[0].Y && j == snake[0].X) {
printf("O");
} else if (i == snake[len - 1].Y && j == snake[len - 1].X) {
printf("X");
} else {
int flag = 0;
for (int k = 1; k < len - 1; k++) {
if (i == snake[k].Y && j == snake[k].X) {
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);
}
void init() {
snake[0].X = WIDTH / 2;
snake[0].Y = HEIGHT / 2;
for (int i = 1; i < len; i++) {
snake[i].X = snake[i - 1].X + 1;
snake[i].Y = snake[i - 1].Y;
}
}
void update() {
for (int i = len - 1; i > 0; i--) {
snake[i].X = snake[i - 1].X;
snake[i].Y = snake[i - 1].Y;
}
switch (dir) {
case 1:
snake[0].Y--;
break;
case 2:
snake[0].Y++;
break;
case 3:
snake[0].X--;
break;
case 4:
snake[0].X++;
break;
}
if (snake[0].X < 0 || snake[0].X >= WIDTH || snake[0].Y < 0 || snake[0].Y >= HEIGHT) {
gameover = 1;
return;
}
for (int i = 1; i < len; i++) {
if (snake[0].X == snake[i].X && snake[0].Y == snake[i].Y) {
gameover = 1;
return;
}
}
if (snake[0].X == snake[len - 1].X && snake[0].Y == snake[len - 1].Y) {
len++;
score += 10;
if (speed > 10) {
speed -= 10;
}
}
}
void input() {
if (_kbhit()) {
switch (_getch()) {
case 'w':
if (dir != 2) {
dir = 1;
}
break;
case 's':
if (dir != 1) {
dir = 2;
}
break;
case 'a':
if (dir != 4) {
dir = 3;
}
break;
case 'd':
if (dir != 3) {
dir = 4;
}
break;
}
}
}
int main() {
init();
while (!gameover) {
draw();
update();
input();
Sleep(speed);
}
gotoxy(WIDTH / 2 - 4, HEIGHT / 2);
printf("Game Over!\n");
gotoxy(WIDTH / 2 - 6, HEIGHT / 2 + 1);
printf("Your score: %d\n", score);
return 0;
}
```
希望这个代码能够帮助您实现一个简单的贪吃蛇小游戏!
阅读全文