帮我用c语言写一个贪吃蛇游戏
时间: 2023-04-02 15:03:56 浏览: 69
好的,我可以为您提供一个贪吃蛇游戏的 C 语言代码。以下是代码:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <windows.h>
#include <time.h>
#define WIDTH 40
#define HEIGHT 20
#define SNAKE_MAX_LENGTH 100
int snakeX[SNAKE_MAX_LENGTH], snakeY[SNAKE_MAX_LENGTH];
int snakeLength = 3;
int foodX, foodY;
int score = ;
int direction = ; // : up, 1: right, 2: down, 3: left
void gotoxy(int x, int y) {
COORD pos = {x, y};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
void drawMap() {
int i, j;
for (i = ; i < HEIGHT; i++) {
for (j = ; j < WIDTH; j++) {
if (i == || i == HEIGHT - 1 || j == || j == WIDTH - 1) {
gotoxy(j, i);
printf("#");
}
}
}
}
void drawSnake() {
int i;
for (i = ; i < snakeLength; i++) {
gotoxy(snakeX[i], snakeY[i]);
printf("*");
}
}
void generateFood() {
srand(time(NULL));
foodX = rand() % (WIDTH - 2) + 1;
foodY = rand() % (HEIGHT - 2) + 1;
gotoxy(foodX, foodY);
printf("@");
}
void updateScore() {
gotoxy(WIDTH + 5, 5);
printf("Score: %d", score);
}
void updateSnake() {
int i;
for (i = snakeLength - 1; i > ; i--) {
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
switch (direction) {
case :
snakeY[]--;
break;
case 1:
snakeX[]++;
break;
case 2:
snakeY[]++;
break;
case 3:
snakeX[]--;
break;
}
}
int checkCollision() {
int i;
if (snakeX[] == || snakeX[] == WIDTH - 1 || snakeY[] == || snakeY[] == HEIGHT - 1) {
return 1;
}
for (i = 1; i < snakeLength; i++) {
if (snakeX[] == snakeX[i] && snakeY[] == snakeY[i]) {
return 1;
}
}
if (snakeX[] == foodX && snakeY[] == foodY) {
score += 10;
snakeLength++;
generateFood();
updateScore();
}
return ;
}
void gameLoop() {
while (1) {
if (kbhit()) {
switch (getch()) {
case 'w':
if (direction != 2) {
direction = ;
}
break;
case 'd':
if (direction != 3) {
direction = 1;
}
break;
case 's':
if (direction != ) {
direction = 2;
}
break;
case 'a':
if (direction != 1) {
direction = 3;
}
break;
}
}
updateSnake();
if (checkCollision()) {
gotoxy(WIDTH / 2 - 4, HEIGHT / 2);
printf("Game Over!");
break;
}
drawMap();
drawSnake();
Sleep(100);
}
}
int main() {
snakeX[] = WIDTH / 2;
snakeY[] = HEIGHT / 2;
snakeX[1] = snakeX[];
snakeY[1] = snakeY[] + 1;
snakeX[2] = snakeX[];
snakeY[2] = snakeY[] + 2;
generateFood();
updateScore();
drawMap();
drawSnake();
gameLoop();
return ;
}
阅读全文