這是一個簡單的C語言貪吃蛇游戲的代碼示例:
#include <stdio.h>
#include <conio.h>
#include <windows.h>
#define WIDTH 20
#define HEIGHT 20
int snakeX[100], snakeY[100];
int snakeLength = 1;
int fruitX, fruitY;
int score = 0;
int gameover = 0;
char direction = 'r';
void setup() {
snakeX[0] = WIDTH / 2;
snakeY[0] = HEIGHT / 2;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
}
void draw() {
system("cls");
for (int i = 0; i < WIDTH + 2; i++)
printf("#");
printf("\n");
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (j == 0)
printf("#");
if (i == snakeY[0] && j == snakeX[0])
printf("O");
else if (i == fruitY && j == fruitX)
printf("F");
else {
int printSnake = 0;
for (int k = 1; k < snakeLength; k++) {
if (i == snakeY[k] && j == snakeX[k]) {
printf("o");
printSnake = 1;
}
}
if (!printSnake)
printf(" ");
}
if (j == WIDTH - 1)
printf("#");
}
printf("\n");
}
for (int i = 0; i < WIDTH + 2; i++)
printf("#");
printf("\n");
printf("Score: %d", score);
}
void input() {
if (_kbhit()) {
switch (_getch()) {
case 'a':
direction = 'l';
break;
case 'd':
direction = 'r';
break;
case 'w':
direction = 'u';
break;
case 's':
direction = 'd';
break;
case 'x':
gameover = 1;
break;
}
}
}
void logic() {
int prevX = snakeX[0];
int prevY = snakeY[0];
int prev2X, prev2Y;
snakeX[0] = snakeX[0] + 1;
snakeY[0] = snakeY[0] + 1;
for (int i = 1; i < snakeLength; i++) {
prev2X = snakeX[i];
prev2Y = snakeY[i];
snakeX[i] = prevX;
snakeY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (direction) {
case 'l':
snakeX[0]--;
break;
case 'r':
snakeX[0]++;
break;
case 'u':
snakeY[0]--;
break;
case 'd':
snakeY[0]++;
break;
}
if (snakeX[0] == fruitX && snakeY[0] == fruitY) {
score += 10;
snakeLength++;
fruitX = rand() % WIDTH;
fruitY = rand() % HEIGHT;
}
if (snakeX[0] >= WIDTH || snakeX[0] < 0 || snakeY[0] >= HEIGHT || snakeY[0] < 0)
gameover = 1;
for (int i = 1; i < snakeLength; i++) {
if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i])
gameover = 1;
}
}
int main() {
setup();
while (!gameover) {
draw();
input();
logic();
Sleep(100);
}
return 0;
}
請注意,這只是一個簡單版本的貪吃蛇游戲,可能還需要進一步優化和完善。您可以根據自己的需求進行修改和擴展。