C语言 贪吃蛇的代码应该怎么写?
时间: 2023-06-06 21:06:11 浏览: 73
初学c语言写的贪吃蛇代码
以下是一个简单的C语言贪吃蛇游戏的代码示例,仅供参考:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
#include <windows.h>
#define WIDTH 50
#define HEIGHT 20
int x, y, fx, fy, flag, score, speed;
char map[HEIGHT][WIDTH];
void gotoxy(int x, int y){
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void init_map(){
int i, j;
for(i = 0; i < HEIGHT; i++){
for(j = 0; j < WIDTH; j++){
if(i == 0 || i == HEIGHT - 1 || j == 0 || j == WIDTH - 1){
map[i][j] = '#';
}else{
map[i][j] = ' ';
}
}
}
}
void init_snake(){
x = WIDTH / 2;
y = HEIGHT / 2;
flag = 1;
map[y][x] = 'O';
map[y][x-1] = 'o';
map[y][x-2] = 'o';
}
void init_food(){
srand(time(NULL));
fx = rand() % (WIDTH - 2) + 1;
fy = rand() % (HEIGHT - 2) + 1;
if(map[fy][fx] != ' '){
init_food();
}else{
map[fy][fx] = '@';
}
}
void show_map(){
int i, j;
system("cls");
printf("Score: %d|Speed: %d\n\n", score, speed);
for(i = 0; i < HEIGHT; i++){
for(j = 0; j < WIDTH; j++){
printf("%c", map[i][j]);
}
printf("\n");
}
}
void move(){
int px, py, i, j;
px = x;
py = y;
if(kbhit()){
switch(getch()){
case 'w': flag = 1; break;
case 's': flag = 2; break;
case 'a': flag = 3; break;
case 'd': flag = 4; break;
}
}
switch(flag){
case 1: y--; break;
case 2: y++; break;
case 3: x--; break;
case 4: x++; break;
}
if(map[y][x] == '#' || map[y][x] == 'o'){
gotoxy(x, y);
printf("X");
printf("\n\nGame Over!\n");
Sleep(1000);
exit(0);
}
if(map[y][x] == '@'){
score += 10;
speed = score / 50 + 1;
map[y][x] = 'O';
init_food();
}else{
map[y][x] = 'O';
for(i = 0; i < HEIGHT; i++){
for(j = 0; j < WIDTH; j++){
if(map[i][j] == 'o'){
map[i][j] = ' ';
}
}
}
}
for(i = y; i < py; i++){
map[i][x] = 'o';
}
for(i = y; i > py; i--){
map[i][x] = 'o';
}
for(i = x; i < px; i++){
map[y][i] = 'o';
}
for(i = x; i > px; i--){
map[y][i] = 'o';
}
}
int main(){
init_map();
init_snake();
init_food();
while(1){
show_map();
move();
Sleep(500 - speed * 50);
}
return 0;
}
阅读全文