写一个贪吃蛇c语言程序
时间: 2024-01-05 10:04:32 浏览: 88
以下是一个简单的贪吃蛇C语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#define WIDTH 60
#define HEIGHT 20
int x, y;
int foodX, foodY;
int length = 2;
int snakeX[100], snakeY[100];
int gameOver = 0;
int score = 0;
void setup(){
x = WIDTH / 2;
y = HEIGHT / 2;
srand(time(NULL));
foodX = rand() % (WIDTH - 2) + 1;
foodY = rand() % (HEIGHT - 2) + 1;
}
void draw(){
system("cls");
for(int i = 0; i < WIDTH; i++){
printf("#");
}
printf("\n");
for(int i = 1; i < HEIGHT - 1; i++){
for(int j = 0; j < WIDTH; j++){
if(j == 0 || j == WIDTH - 1){
printf("#");
} else if(i == foodY && j == foodX){
printf("O");
} else if(i == y && j == x){
printf("X");
} else {
int print = 0;
for(int k = 0; k < length; k++){
if(snakeX[k] == j && snakeY[k] == i){
printf("x");
print = 1;
}
}
if(!print){
printf(" ");
}
}
}
printf("\n");
}
for(int i = 0; i < WIDTH; i++){
printf("#");
}
printf("\n");
printf("Score: %d\n", score);
}
void input(){
if(kbhit()){
switch(getch()){
case 'a':
x--;
break;
case 'd':
x++;
break;
case 'w':
y--;
break;
case 's':
y++;
break;
case 'x':
gameOver = 1;
break;
}
}
}
void logic(){
int prevX = snakeX[0];
int prevY = snakeY[0];
int prev2X, prev2Y;
snakeX[0] = x;
snakeY[0] = y;
for(int i = 1; i < length; i++){
prev2X = snakeX[i];
prev2Y = snakeY[i];
snakeX[i] = prevX;
snakeY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
if(x == foodX && y == foodY){
length++;
score += 10;
foodX = rand() % (WIDTH - 2) + 1;
foodY = rand() % (HEIGHT - 2) + 1;
}
if(x < 1 || x > WIDTH - 2 || y < 1 || y > HEIGHT - 2){
gameOver = 1;
}
for(int i = 0; i < length; i++){
if(snakeX[i] == x && snakeY[i] == y){
gameOver = 1;
}
}
}
int main(){
setup();
while(!gameOver){
draw();
input();
logic();
Sleep(100);
}
printf("Game over!\n");
printf("Your score is: %d\n", score);
return 0;
}
```
这个程序使用了简单的ASCII字符图形来显示场景,并在控制台中运行。玩家使用方向键来控制贪吃蛇,吃掉食物并增加分数,当贪吃蛇撞到墙壁或自身时游戏结束。
阅读全文